<?php

namespace app\shop\model;


use app\admin\model\ShopModel;
use app\admin\model\ShopRefundOrderModel;
use app\admin\model\SysModel;
use app\crm\model\Customer;
use app\crm\model\CustomerAccount;
use app\crm\model\CustomerPrestockExit;
use app\crm\model\CustomerPrestockGoods;
use app\crm\model\FollowRecord;
use app\admin\model\Common;
use app\crm\model\ProductItem;
use app\crm\model\SendMsgModel;
use app\crm\model\Service;
use app\crm\model\ShopGoods;
use app\shop\model\ShopRefundOrderGoods;
use app\mini\model\AdminUser;
use app\shop\model\AddOrderLog;
use Kingdee\Kingdee;
use mysql_xdevapi\Exception;
use think\facade\Db;
use think\model\concern\SoftDelete;
use app\common\traits\ActionRecordTrait;
use app\shop\model\RefundPayModel;
use app\shop\model\TurnRefund;
use app\services\SendMsg;


/**
 * 订单模型
 * @package app\shop\model
 * @author LIU
 * @create 2021-10-01
 */

class Refund extends Common

{

    use ActionRecordTrait;



    /**

     * 表名

     * @var string

     */

    protected $name = 'shop_refund_order';

    protected $defaultSoftDelete = 0;



    /**

     * 获取sku信息

     * @return \think\model\relation\hasOne

     * @author SL

     * @create 2021-05-27 15:04

     */

    public function orderGoods()

    {

        return $this->hasOne(Goods::class,'id');

    }









    /**

     * 获取订单列表

     * @param  array $request 请求参数

     * @return array

     * @author LIU

     * @create 2021-10-26

     */

    public function getModeList($request)
    {

        try {
            $refund_mode = $request['refundMode'] ?? '';

            $where = [];

            array_push($where,['status','=',1]);

            if($refund_mode == '1' || $refund_mode == '3' ){

                array_push($where,['refund_mode','in',['02','03']]);

            }

            $list = Db::name('refund_mode')->where($where)->select();

            $data              = [];

            $data['list']      = $list ?? [];

            return $data;

        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }


    }











    /**

     * 获取订单列表

     * @param  array $request 请求参数

     * @return array

     * @author LIU

     * @create 2021-10-26

     */

    public function getDataList($request)

    {



        try {

            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $person_shop_id = isset($request['person_shop_id'])?$request['person_shop_id']:0; //当前登陆人所属门店id
            $admin_user_id = isset($request['admin_user_id'])?$request['admin_user_id']:0;//当前登陆人id

            $request = $this->fmtRequest($request);





            $map     = $request['map'] ?? [];

            $where   = [];

            $is_show_add = true;


            if (!isset($map['type'])) {
                $this->error = '请传入type类型';
                return [];
            }

            if (!in_array($map['type'],[1,2,3]))
            {
                $this->error = 'type类型不正确';
                return [];
            }


            $id = isset($map['id']) && $map['id'] ? $map['id'] : [];
            if ($id) {
                if (!is_array($id)) {
                    $id = [$id];
                }
                array_push($where, ['o.id', 'in', $id]);
            }

            // array_push($where, ['o.status', '<>', 3]);//排除已作废的

            $type      =$map['type']; // 订单类型 1退款单 2退货单 3收款单

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            //$refund_order_no     = isset($map['refund_order_no']) && $map['refund_order_no'] ? trim($map['refund_order_no']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $status       = isset($map['status']) && intval($map['status']) ? intval($map['status']) : 0; // 订单状态

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            $is_pay = $map['is_pay'] ?? ''; // 订单是否支付

            $display_cannel = isset($map['display_cannel']) && intval($map['display_cannel']) ? intval($map['display_cannel']) : 0; // 订单状态

            // echo "<pre>";
            // print_r($map);
            // echo "</pre>";

            // echo "是否支付：".$is_pay;
            // exit;

            // 获取客户数据权限 的客户名称

            if ($shopIds) {
                array_push($where, ['o.shop_id', 'in', $shopIds]);
            }

            if ($uid) {
                //门店id搜索
                array_push($where, ['o.uid', '=', $uid]);
            }

            if ($type) {
                //门店名称搜索
                array_push($where, ['o.type', '=', $type]);
            }

            if ($shop_id) {
                //门店名称搜索
                array_push($where, ['o.shop_id', '=', $shop_id]);

            }

            if ($consignee) {
                // 客户名称搜索
                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);
            }

            if ($shop_name) {
                //门店名称搜索
                array_push($where, ['o.shop_name', 'like', '%'.$shop_name.'%']);
            }

            if ($consignee) {
                // 客户搜索
                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);
            }

            if ($status != -1) {
                array_push($where, ['o.status', '=', $status]);
            }

            if ($is_pay == '0') {
                array_push($where, ['o.is_pay', '=', $is_pay]);
            }

            // if ($refund_order_no) {

            // array_push($where, ['o.refund_order_no', '=', $refund_order_no]);

            // }



            // 时间

            if($start_time && $end_time) {
                array_push($where, ['o.deal_time', 'between', "$start_time,$end_time"]);
            }

            if ($business_type) {
                //业务类型搜索
                array_push($where, ['o.business_type', '=', $business_type]);
            }

            if ($order_type) {
                //订单类型搜索
                array_push($where, ['o.order_type', '=', $order_type]);
            }

            //退货单以订单总额搜索
            if ($type==2) {
                if ($low_total && !$large_total) {
                    array_push($where, ['o.total_amount', 'egt', $low_total]);
                }
                if (!$low_total && $large_total) {
                    array_push($where, ['o.total_amount', 'elt', $large_total]);
                }

                if ($low_total && $large_total) {
                    array_push($where, ['o.total_amount', 'between', "$low_total,$large_total"]);
                }
            }else {
                //收款单 退款单以实际金额搜索
                if ($low_total && !$large_total) {
                    array_push($where, ['o.pay_amount', 'egt', $low_total]);
                }

                if (!$low_total && $large_total) {
                    array_push($where, ['o.pay_amount', 'elt', $large_total]);
                }

                if ($low_total && $large_total) {
                    array_push($where, ['o.pay_amount', 'between', "$low_total,$large_total"]);
                }
            }



            $sqlQuery = $this->alias('o')

                ->where($where);

            // $dataCount  = $sqlQuery->count();


            if($display_cannel == 0)
            {
                array_push($where,['o.status','<>',3]);

            }

            if (in_array($type,[1,3])) {


                $field = ['o.id','o.consignee', 'o.order_type','o.is_lock','business_type','o.shop_name','o.create_time','o.shop_id','o.deal_time','o.type','o.type','o.sale_name','c.king_no','g.refund_mode_name','g.pay_price','g.gift_price','g.shop_transfer_price','o.refund_type','o.refund_type_plus','o.is_pay','o.is_pay_time','o.status','o.extra_type'];
                $dataCount = $this->alias('o')->field($field)->where($where)
                    ->join('customer c', 'o.uid = c.id')
                    ->join('shop_refund_order_goods g', 'o.id = g.order_id')
                    ->count();

//                echo Db::name('shop_refund_order')->getlastsql();die;

            }else{
                $field = ['o.id','o.goods_price','o.consignee', 'o.is_lock','o.total_amount','o.shop_name','o.order_type','o.business_type','o.create_time','o.shop_id','o.sale_name','o.deal_time','o.type','c.king_no','o.refund_type','o.refund_type_plus','o.is_pay','o.is_pay_time','o.status','o.extra_type'];
                $dataCount = $this->alias('o')->field($field)->where($where)
                    ->join('customer c', 'o.uid = c.id')
                   ->count();
            }

            $sum_ben_amount=0;

            $sum_zeng_amount=0;

            $sum_amount  =0;

            if ($dataCount) {
                // 订单列表
                if($display_cannel == 0)
                {
                    $sqlQuery = $sqlQuery->where('o.status','<>',3);
                }

                //退款单 收款单
                if (in_array($type,[1,3])) {
                    $sum_ben_amount  = $this->alias('o')

                        ->where($where)->where('o.status','<>',3)->sum('o.pay_amount');

                    $sum_zeng_amount  = $this->alias('o')

                        ->where($where)->where('o.status','<>',3)->sum('o.gift_amount');

                    // $sum_ben_amount  = $sqlQuery->sum('o.pay_amount');

                    // $sum_zeng_amount  = $sqlQuery->sum('o.gift_amount');

                    $field = ['o.id','o.consignee', 'o.order_type','o.is_lock','g.data_business_type as business_type','g.data_business_two_type as business_two_type','o.shop_name','o.create_time','o.shop_id','o.deal_time','o.type','o.type','o.sale_name','c.king_no','g.refund_mode_name','g.pay_price','g.gift_price','g.shop_transfer_price','o.refund_type','o.refund_type_plus','o.is_pay','o.is_pay_time','o.status','o.extra_type'];


                    $list = $sqlQuery->field($field)

                        ->join('customer c', 'o.uid = c.id')

                        ->join('shop_refund_order_goods g', 'o.id = g.order_id')

                        ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                        ->order('id DESC')

                        ->select()->toArray();

                }else{

                    // $sum_amount  =$sqlQuery->sum('o.total_amount');

                    $sum_amount  = $this->alias('o')

                        ->where($where)->where('o.status','<>',3)->sum('o.total_amount');

                    //退货单

                    $field = ['o.id','o.goods_price','o.consignee', 'o.is_lock','o.total_amount','o.shop_name','o.order_type','o.business_type','o.business_two_type','o.create_time','o.shop_id','o.sale_name','o.deal_time','o.type','c.king_no','o.refund_type','o.refund_type_plus','o.is_pay','o.is_pay_time','o.status','o.extra_type'];


                    $list = $sqlQuery->field($field)

                        ->join('customer c', 'o.uid = c.id')

                        ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                        ->order('id DESC')

                        ->select()->toArray();

                }

                if ($list) {
                    $order_type = [
                        0=>'',
                        1=>'初诊',
                        2=>'复诊',
                        3=>'再消费',
                        4=>'诊疗',
                        5=>'其他',
                    ];
                    $businessType = Db::name('customer_balance_category')->column('name','id');
                    $businessTwoType = [1=>'身体项目',2=>'皮肤项目'];
                    foreach($list as &$v){

                        if (in_array($type,[1,3])){
                            $v['price_sum'] = bcadd(bcadd($v['pay_price'],$v['gift_price'],2),$v['shop_transfer_price'],2);
                        }

                        $v['order_type'] =  isset($order_type[$v['order_type']])?$order_type[$v['order_type']]:'';
                        $v['business_type'] = $businessType[$v['business_type']]??'暂无数据';
                        $v['business_two_type'] = $businessTwoType[$v['business_two_type']]??'暂无数据';

                        // $v['refund_type'] = $v['refund_type'] ?? '';

                        $refund_type = '';
                        if($v['refund_type']=='101.01'){
                            $refund_type = '店面转诊';
                        }elseif ($v['refund_type']=='101.02') {
                            if($v['type']=='1'){
                                $refund_type = '退款';
                            }else if($v['type']=='3'){
                                $refund_type = '收款';
                            }

                        }else {

                            if($v['type']=='1'){
                                $refund_type = '退款调整';
                            }else if($v['type']=='3'){
                                $refund_type = '收款调整';
                            }
                        }

                        $v['refund_type']=$refund_type;

                        $v['deal_time']=date('Y-m-d', $v['deal_time']);

                        if($v['is_pay']=='0'){

                            $v['is_pay']='未支付';

                            $v['is_pay_time']='';

                        }elseif($v['is_pay']=='1'){

                            if($v['refund_type_plus']=='2'){

                                $v['is_pay']='已支付';

                                $v['is_pay_time']='-';

                            }else{

                                $v['is_pay']='已支付';

                                $v['is_pay_time']=date('Y-m-d H:i:s', $v['is_pay_time']);

                            }


                        }else {
                            $v['is_pay']='-';

                            $v['is_pay_time']='-';
                        }

                        if($v['refund_type_plus']=='1'){
                            $v['refund_type_plus']='扫码支付';
                        }elseif($v['refund_type_plus']=='2'){
                            $v['refund_type_plus']='传统支付';
                        }elseif($v['refund_type_plus']=='3'){
                            $v['refund_type_plus']='线上支付';
                        }else {
                            $v['refund_type_plus']='-';
                        }

                        switch ($v['status']) {
                            case '1':
                                $v['status_msg'] = '已退款';
                                break;
                            case '2':
                                $v['status_msg'] = '已下推';
                                break;
                            case '3':
                                $v['status_msg'] = '已作废';
                                break;
                            default:
                                $v['status_msg'] = '未完成';
                                break;
                        }
                        if($v['extra_type']==1&&$v['business_type']=="疤痕") {
                            $v['extra_type']="青春痘";
                        }else{
                            $v['extra_type']="";
                        }

                    }

                }

            }

            $permission = get_user_permission_menu($userId,'order_list_tag');

            $data              = [];

            $data['menu_list'] = $permission ? $permission : [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            $data['is_show_add'] = true;


            if($start_time && $end_time) {

                if (in_array($type, [1, 3])) {

                    $data['sum_ben_amount'] = $sum_ben_amount ?? 0;

                    $data['sum_zeng_amount'] = $sum_zeng_amount ?? 0;

                } else {

                    $data['sum_amount'] = $sum_amount ?? 0;

                }

            }

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }



    /**

     * 订单主要详情

     * @param array $request

     * @return array

     * @author SL

     * @create 2021-06-02

     */

    public function getDataDetail($request)

    {

        try {

            $id = $request['order_id'] ?? 0;

            if(!$id){

                $this->error = '请传入订单id';

                return [];

            }

            $type = $request['type'] ?? 0;

            if(!$type){

                $this->error = '请传入退款单类型';

                return [];

            }

            $detail = [];

            if (in_array($type,[1,3]))

            {

                $field = ['id,type,consignee,refund_order_no,operator_name,shop_name,business_type,order_type,status,total_amount,pay_amount,gift_amount,shop_transfer_amount,is_treatment,referral_shop_name,
                
                            deal_time,create_time,king_push_time,king_status,description,sales_policy,refund_type,is_pay,refund_type_plus,shop_id,order_class,refunder,refund_account,business_two_type', 'is_experience,is_outreach,outreahc_name,is_introduction,introduction_name', 'sales_name','settlement_name','market_name','king_num','combo',
                    'experience_id,outreahc_id,introduction_id,experience_name,extra_type,sale_id,sale_name,refund_type_plus,shanghu_type,project_type' ];

            }else
            {

                $field = ['id,type,refund_order_no,consignee,operator_name,shop_name,business_type,income_type,order_type,status,total_amount,gift_amount,shop_transfer_amount,refund_type_plus,shanghu_type,

            pay_amount,deal_time,create_time,king_push_time,king_status,sales_policy,shop_id,order_class,refunder,refund_account,business_two_type', 'is_experience,is_outreach,outreahc_name,is_introduction,introduction_name', 'sales_name','settlement_name','market_name','sale_name','king_num','delivery_name,extra_type,sale_id,sale_name,project_type'];

            }

            $detail = $this->where('id',$id)->field($field)->find();

            // echo "<pre>";
            // print_r($detail);
            // echo "</pre>";
            // exit;


            if($detail){

                $business_two_type = [
                    0=>"暂无",
                    1=>"身体项目",
                    2=>"皮肤项目"
                ];
                $detail['business_two_type_text'] = $business_two_type[$detail['business_two_type']]??'暂无';
                $order_class = [
                    '0'=>'暂无', '1'=>'生美', '2'=>'医美',
                ];
                $detail['order_class'] = (string)$detail['order_class'];
                $detail['order_class_text'] =  $order_class[$detail['order_class']]??'暂无';
                $detail['shop_type'] = DB::name('shop')->where('shop_id',$detail['shop_id'])->value('shop_type');

                $detail['is_outreach_text'] = $detail['is_outreach'] == 1?'是':'否';
                $detail['is_experience_text'] = $detail['is_experience'] == 1?'是':'否';
                $detail['is_introduction_text'] = $detail['is_introduction'] == 1?'是':'否';

                $project_type = [
                    1=>'手术', 2=>'注射', 3=>'光电', 4=>'生美皮肤', 5=>'身体'
                ];
                $detail['project_type_name'] = isset($project_type[$detail['project_type']])?$project_type[$detail['project_type']]:'暂无';


                // var_dump($detail['is_pay']);
                $today = date('Y-m-d');

                $create_date = date('Y-m-d',strtotime($detail['create_time']));

                $refund_type_plus = $detail['refund_type_plus'] ?? '';


                if($today == $create_date && $detail['is_pay'] == '1' && $refund_type_plus != '2'){
                    // echo "允许退款";

                    $detail['is_cancel'] = '1';
                }else{
                    // echo "不许退款";

                    $detail['is_cancel'] = '0';
                }
                // exit;

                // 时间转化

                $detail['king_push_time'] = $detail['king_push_time'] ? date('Y-m-d H:i:s', $detail['king_push_time']) : '';

                $detail['deal_time'] = $detail['deal_time'] ? date('Y-m-d', $detail['deal_time']) : '';

                $detail['cancel_time'] = $detail['cancel_time'] ? date('Y-m-d H:i:s', $detail['cancel_time']) : '';

                $businessType = Db::name('customer_balance_category')->column('name','id');
                $detail['business_type']    = $businessType[$detail['business_type']]??'暂无数据';
                if($detail['business_type'] == "疤痕"&&$detail['extra_type'] == 1)
                {
                    $detail['business_type'] = "青春痘";
                }

                $type_store = [
                    1=>'初诊', 2=>'复诊',3=>'再消费',4=>'诊疗',5=>'其他'
                ];
                $detail['order_type']    = $type_store[$detail['order_type']] ??'';
                $shanghuType=[
                    0=>'无', 1=>'公户', 2=>'私户'
                ];
                if(!empty($detail['shanghu_type']))
                {
                    $detail['shanghu_type']=$shanghuType[$detail['shanghu_type']];
                }
                $refundTypePlus=[
                    0=>"未知", 1=>"通联支付", 2=>"传统支付", 3=>"通联远程"
                ];
                if(!empty($detail['refund_type_plus']))
                {
                    $detail['refund_type_plus']=$refundTypePlus[$detail['refund_type_plus']];
                }

                switch ($detail['status']) {

                    case '1':

                        $detail['status_msg'] = '已退款';

                        break;

                    case '2':

                        $detail['status_msg'] = '已下推';

                        break;

                    case '3':

                        $detail['status_msg'] = '已作废';

                        break;

                    default:

                        $detail['status_msg'] = '待退款';

                        break;

                }

            }

            else{

                $this->error = '订单不存在';

                return false;

            }

            $userId  = $request['user_id'] ?? 0;

            $permission = get_user_permission_menu($userId,'order_list_tag');

            $detail['menu_list'] = $permission ? $permission : [];

            return $detail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }



    /**
     * 订单商品详情
     * @param array $request
     * @return array
     * @author SL
     * @create 2021-06-02
     */

    public function getGoodsDataDetail($request)
    {

        try {
            $id = $request['order_id'] ?? 0;
            if(!$id){
                throw new Exception('请传入订单id');

            }
            $type = $request['type'] ?? 0;
            if(!$type){
                throw new Exception('请传入退款单类型');
            }
            $detail = [];
            $list =[];
            $detail = Db::name('shop_refund_order')->field('id')->where('id',$id)->find();
            if($detail)
            {
                if (in_array($type,[1,3])) {
                    $field = ['id,order_id,refund_mode,refund_mode_name,bank_number,data_business_type,data_sales_policy,descs,pay_price,gift_price,shop_transfer_price,data_business_type,data_business_two_type,goods_alias_name,is_prestock,number'];
                }
                else {
                    $field = ['id,order_id,goods_id,goods_name,pay_price,kingdee_code,unit_code,goods_deal_time,is_gift,descs,house_code,house_code_name,shop_transfer_price,data_business_type,data_business_two_type,goods_alias_name,is_prestock,number,gift_price,shop_transfer_price,refund_principal_price,service_goods_str'];
                }

                // 订单商品
                $detail['goodsList'] = [];
                $list = Db::name('shop_refund_order_goods')
                    ->where('order_id', $id)
                    ->order('id DESC')
                    ->field($field)->select()->toArray();
                $business_type = [
                    1=>'疤痕',2=>'项目', 3=>'青春痘', 4=>'护肤品'
                ];
                $business_two_type = [
                    1=>'身体项目', 2=>'皮肤项目'
                ];

                $is_prestock = [
                    1=>'是', 2=>'否', 0=>'无',
                ];
                foreach ($list as $key => &$value)
                {
                    $value['data_business_type_text'] = isset($business_type[$value['data_business_type']])?$business_type[$value['data_business_type']]:'';
                    $value['data_business_two_type_text'] = isset($business_two_type[$value['data_business_two_type']])?$business_two_type[$value['data_business_two_type']]:'';
                    $value['data_business_two_type'] = !empty($value['data_business_two_type']) ?$value['data_business_two_type']:'';
                    $value['is_refund_prestock'] = isset($is_prestock[$value['is_prestock']])?$is_prestock[$value['is_prestock']]:'';
                    if (isset($value['goods_deal_time']))
                    {
                        $value['goods_deal_time'] = date("Y-m-d",$value['goods_deal_time']);
                    }
                    $value['return_num'] = $value['number'];
                    $value['children'] = [];


                    if(!empty($value['service_goods_str'])){

                        $children = json_decode($value['service_goods_str'],1);
                        $childrens = [];
                        foreach ($children as $k=>$v){
                            $child=[];
                            $child['goods_name'] =$v['name'];
                            $child['goods_alias_name'] = '----';
                            $child['pay_price'] = $v['goods_price'];
                            $child['kingdee_code'] = $value['kingdee_code'];
                            $child['is_gift'] = '----';
                            $child['data_business_type_text'] = '----';
                            $child['is_refund_prestock'] = '----';
                            $child['return_num'] = '----';
                            $child['refund_principal_price'] = '----';
                            $child['gift_price'] = '----';
                            $child['descs'] = $value['descs'];
                            array_push($childrens,$child);
                        }
                        $value['children'] = $childrens;
                    }
                }

            } else{
                throw new \Exception('订单不存在');
            }

            if ($list) {
                $detail['goodsList'] = $list;
            }

            return $detail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }




    /*
     *  订单修改 -收款单、退款单、退货单
    */
    public function updateDataDetail($request)
    {

        Db::startTrans();
        try {
            $order = $this->find($request['id']);
            if(empty($order)){
                throw new \Exception('订单不存在');
            }

            if($order['type']!=2){
                if(empty($order->is_pay)) {
                    throw new \Exception('订单未完成');
                }
            }

            if($order->status == 3 ){
                throw new \Exception('该订单已经作废，无法修改');
            }

            //退货单
            if($order['type'] ==2){
                $order_goods = $request['order_goods']??[];

                foreach($order_goods as $k=>$v){
                    $update = [
                        'goods_alias_name'=>$v['goods_alias_name'],
                    ];
                    $res = ShopRefundOrderGoods::where('id',$v['id'])->update($update);

                }
            }

            if(empty($request['is_experience']))//是否体验
            {
                $order->is_experience = 0;
                $order->experience_id = 0;
                $order->experience_name = "";
            }else{
                if(empty($request['experience_id'])) {
                    throw new \Exception('未选择体验人');
                }else{
                    $staff= ShopPerson::field('id,name')->where('id',$request['experience_id'])->find();
                    if(empty($staff)) {
                        throw new \Exception('体验人不存在');
                    }else{
                        $order->is_experience = $request['is_experience'];
                        $order->experience_id = $request['experience_id'];
                        $order->experience_name = $staff['name'];
                    }
                }
            }

            if(empty($request['is_introduction']))//是否转介绍
            {
                $order->is_introduction = 0;
                $order->introduction_id = 0;
                $order->introduction_name = "";
            }else{
                if(empty($request['introduction_id'])) {
                    throw new \Exception('未选择转介绍人');
                }else{
                    $staff = ShopPerson::field('id,name')->where('id',$request['introduction_id'])->find();
                    if(empty($staff)) {
                        throw new \Exception('转介绍人不存在');
                    }else{
                        $order->is_introduction = $request['is_introduction'];
                        $order->introduction_id = $request['introduction_id'];
                        $order->introduction_name = $staff['name'];
                    }
                }
            }

            if(empty($request['is_outreach']))//是否外部联系
            {
                $order->is_outreach = 0;
                $order->outreahc_id = 0;
                $order->outreahc_name = "";
            }else{
                if(empty($request['outreahc_id'])) {
                    throw new \Exception('未选择外部联系人');
                }else{
                    $staff=ShopPerson::field('id,name')->where('id',$request['outreahc_id'])->find();
                    if(empty($staff)) {
                        throw new \Exception('外部联系人不存在');
                    }else{
                        $order->is_outreach = $request['is_outreach'];
                        $order->outreahc_id = $request['outreahc_id'];
                        $order->outreahc_name = $staff['name'];
                    }
                }
            }
            //开单人
            if(empty($request['sale_id'])){
                $order->sale_id = 0;
                $order->sale_name = "";
            }else{
                $staff = ShopPerson::field('id,name')->where('id',$request['sale_id'])->find();
                if(empty($staff)) {
                    throw new \Exception('开单人不存在');
                }else{
                    $order->sale_id = $request['sale_id'];
                    $order->sale_name = $staff['name'];
                }
            }

            //变更为新单时-转介绍订单有问题
            if($request['order_type'] ==1 && $request['order_type'] != $order->order_type ) {
                $customer = Customer::where('id', $order->uid)->find();
                $cj_time = $order->deal_time;
                $cj_money = $order->pay_amount;
                $cj_order_id = $order->id;
                // 新单 新增触发 改变顾客的 新单时间和 金额的
                if ($cj_time > 0 && $cj_money > 0 && $cj_order_id > 0) {
                    $customerSaveData = $customerSaveTurnData = [];
                    // 新单数据的存储
                    if ($customer['cj_time'] == 0) {
                        $customer['cj_time'] = $cj_time;
                        $customer['cj_money'] = $cj_money;
                        $customer['cj_order_id'] = $cj_order_id;
                        $customer->save();
                    }

                    //转介绍顾客的新单数据处理----2022.04.19
                    $customerSaveTurnData['turn_cjtime'] = $cj_time;
                    $customerSaveTurnData['turn_cjmoney'] = $cj_money;
                    $customerSaveTurnData['turn_order_id'] = $cj_order_id;
                    if (!empty($customerSaveTurnData)) {
                        Db::name('customer')->where('turn_customerid', $customer['id'])->update($customerSaveTurnData);
                    }
                }
            }


            //改为补单时
            if($request['order_type'] ==2){
                Db::name('customer')->where('turn_order_id',$order->id)->where('turn_customerid',$order->uid)->update(['turn_order_id'=>0,'turn_cjtime'=>0,'turn_cjmoney'=>0]);
                Db::name('customer')->where('id',$order->uid)->where('cj_order_id',$order->id)->update(['cj_order_id'=>0,'cj_money'=>0,'cj_time'=>0]);
            }

            $order->order_type=$request['order_type'];
            $order->order_class = $request['order_class'] ?? 0;
            $res = $order->save();


            if($res) {
                Db::commit();
                return ['msg'=>"更新完毕",'code'=>200];
            }else{
                throw new \Exception('更新失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return [];

        }
    }








    /**
     * 创建收/退款单
     * @param  array $request 请求参数
     * @return bool
     * @author LIU
     * @create 2021-12-12
     */

    public function addData($request)
    {

        try {
            $validate = new \app\shop\validate\Refund();
            if (!$validate->scene('createOrder')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }
        }catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }

        Db::startTrans();
        try {

            $deal_time = strtotime($request['deal_time']);
            $orderVerfiy = $this->orderVerfiy(5,$deal_time);
            if(!$orderVerfiy){
                throw new \Exception('订单不可创建');
            }
            //检查订单是否已经录入
            if(!empty($request['api_order_id'])) {
                $check_count = ShopRefundOrderModel::where('api_order_id',$request['api_order_id'])->count();
                if($check_count > 0) {
                    throw new \Exception('订单已经创建');
                }
            }

            $customer_data= Customer::with(['info'=>function($query)use($request){
                $query->field('id,type_store');
            }])->where('id',$request['uid'])->field('id,source_id,source_type_id')->find();
            if($customer_data['info']['type_store'] == 4){
                throw new \Exception('订单无法创建');
            }



            $request['refund_type_plus'] = $request['refund_type_plus'] ?? '2';
            $is_pay = '1'; //默认传统录单
            if(in_array($request['refund_type_plus'],[1,3])){
                //  1-扫码盒子支付和 3-线上扫码支付";
                $is_pay = '0';
            }

            $orderDataList = $request['goodsList']; //订单明细
            $pay_price= $gift_price = [];

            $shop = ShopModel::where('shop_id',$request['shop_id'])->lock(true)->field('type,keycode,shop_type,is_sichuan,bank_card,market_id,market_name')->find();//判断直营 加盟

            $modes = Db::name('refund_mode')->where('status',1)->cache(600)->field('refund_mode,refund_mode_name')->select()->toArray();
            $modes_key = array_column($modes,null,'refund_mode');
            $modes = array_column($modes,'refund_mode');
            $time = time();

            $coefficient=1;//数据统计计算系数
            $is_transfer=0;
            foreach ($orderDataList as $key => $val) {
                //服务类型判断
                if (!isset($val['refund_mode']) || empty($val['refund_mode']) || !in_array($val['refund_mode'],$modes)) {
                    throw new \Exception('结算方式必填');
                }

                $pay_price[] = $val['pay_price'];
                $gift_price[] =$val['gift_price'];
            }


            //直营店门店编码 发货组织编码 销售组织编码必传
            if (!$shop['keycode']|| !isset($request['sales_organization'])|| !$request['sales_organization'] || !isset($request['settlement_organization'])|| !$request['settlement_organization'])
            {
                throw new \Exception('直营店门店编码或发货组织编码或销售组织编码不存在，请联系总部解决');
            }

            $pay_amount = bcadd(array_sum($pay_price),0,2);
            $gift_amount = bcadd(array_sum($gift_price),0,2);
            $total_amount = bcadd($pay_amount,$gift_amount,2);


            $operator_name= AdminUser::where(['id' => $request['operator_id']])->value('realname');

            // 验证
            $data = [
                'uid'                => trim($request['uid']), // 客户
                'uid_source_type_id' => $customer_data['source_type_id']??0,
                'source_id'          => $customer_data['source_id']??0,
                'consignee'          => trim($request['consignee']), // 收货人
                'refund_order_no'    => time().rand(1000,9999), // 订单编号, // 订单号
                'sale_id'            => $request['sale_id'], // 销售员id
                'sale_name'          => trim($request['sale_name']), // 销售员姓名
                'shop_id'            => $request['shop_id'], // 门店id
                'shop_name'          => trim($request['shop_name']), // 门店名称
                'referral_shop_id'   =>  0, // 转诊门店id
                'referral_shop_name' => '', // 转诊门店名称
                'coefficient'        => $coefficient, // 统计数据计算系数
                'shop_type'          => $shop['shop_type'], // 门店属性
                'market_id'          => $shop['market_id'], // 市场id
                'market_name'        => $shop['market_name'], // 市场名称
                'is_treatment'       => $request['is_treatment'], // 是否疗程  1是  2否 0未选择
                'operator_id'        => $request['operator_id'],//制单员id
                'operator_name'      => $operator_name,//制单员姓名
                'create_time'        => $time, // 创建时间
                'deal_time'          => strtotime($request['deal_time']), // 成交日期
                'total_amount'       =>  $total_amount, // 应退（收）金额
                'pay_amount'         =>  $pay_amount , // 实退（收）本金
                'gift_amount'          => $gift_amount, // 实退（收）赠金
                'shop_transfer_amount' =>  0, // 实退（收）店转
                'description'          => isset($request['description']) ? $request['description'] : '', // 订单描述
                'order_type'           => $customer_data['info']['type_store']??'', // 订单类型 1新单 2补单
                'business_type'        => 0, // 业务类型 1项目 2疤痕 3青春痘 4护肤品
                'sales_policy'         => isset($request['sales_policy'])? $request['sales_policy'] : '', // 销售政策编码
                'refund_type'          => isset($request['refund_type'])? $request['refund_type'] : '', // 退款类型 101.01 店转  101.02 退款

                'type'                 => $request['type'],//退款单类型 1退款单 2退货单

                'sales_organization'       => isset($request['sales_organization']) ? $request['sales_organization'] : 0, // 销售组织编码
                'sales_name'       => isset($request['sales_name']) ? $request['sales_name'] : '', // 销售组织名称

                'settlement_organization'       => isset($request['settlement_organization']) ? $request['settlement_organization'] : 0, // 结算组织编码
                'settlement_name'       => isset($request['settlement_name']) ? $request['settlement_name'] : '', // 结算组织名称

                'is_experience'     => $request['is_experience'], // 是否体验 0否 1是
                'experience_id'       => isset($request['experience_id']) ? $request['experience_id'] : 0, // 体验人id
                'experience_name'       => isset($request['experience_name']) ? $request['experience_name'] : '', // 体验人姓名

                'is_outreach'       => $request['is_outreach'], // 是否外联 0否 1是
                'outreahc_id'       => isset($request['outreahc_id']) ? $request['outreahc_id'] : 0, // 外联人id
                'outreahc_name'       => isset($request['outreahc_name']) ? $request['outreahc_name'] : '', // 外联人姓名

                'is_introduction'       => $request['is_introduction'], // 是否转介绍 0否 1是
                'introduction_id'       => isset($request['introduction_id']) ? $request['introduction_id'] : 0, // 转介绍人id
                'introduction_name'       => isset($request['introduction_name']) ? $request['introduction_name'] : '', // 转介绍人姓名

                'combo'       => isset($request['combo']) ? $request['combo'] : 0, // 退款审批类型 0没选   1项目退款 2疤痕退款

                'refund_type_plus'           => $request['refund_type_plus'] ?? '', // 收款方式  通联支付  传统支付  通联远程

                'shanghu_type'           => $request['shanghu_type'] ?? '', // 商户分类1是公户，2是私户

                'is_pay'           => $is_pay, // 是否支付：0未支付，1已支付

                'order_class' =>  0, //订单分类   1 生美 2 医美

                'refunder' => $request['refunder'] ?? '', //对方账户名称

                'refund_account' => $request['refund_account'] ?? '', //对方银行账号

                'refund_bank' => $request['refund_bank']??'',   //对方开户行

                'api_type' => $request['api_type'] ?? 0, //0中台系统 1商城积分兑换订单 2商城普通订单

                'api_order_id' => $request['api_order_id'] ?? '', //商城订单ID

            ];

            $data['extra_type']=0;

            // 需要放开
            $order = $this->create($data);

            if ($order) {

                $consumption_amount_bj_array = $consumption_amount_zeng_array  = [];
                $consumption_amount = 0.00;

                foreach ($orderDataList as $k => $v) {
                    $orderGoodsList[$k]['order_id'] = $order->id;
                    $orderGoodsList[$k]['create_time'] = $time;
                    $orderGoodsList[$k]['refund_mode'] = $v['refund_mode'];
                    $orderGoodsList[$k]['refund_mode_name'] = isset($modes_key[$v['refund_mode']])?$modes_key[$v['refund_mode']]['refund_mode_name']:"";
                    $orderGoodsList[$k]['bank_number'] = $shop['bank_card'];
                    $orderGoodsList[$k]['data_business_type'] = 0;
                    $orderGoodsList[$k]['data_business_two_type'] = 0;
                    $orderGoodsList[$k]['data_sales_policy'] =isset($v['data_sales_policy'])?$v['data_sales_policy']:"";  //销售政策编码
                    $orderGoodsList[$k]['pay_price'] = $v['pay_price'] ?? 0;
                    $orderGoodsList[$k]['gift_price'] = $v['gift_price'] ?? 0;
                    $orderGoodsList[$k]['descs'] = $v['descs'];

                    array_push($consumption_amount_bj_array,$orderGoodsList[$k]['pay_price']);
                    array_push($consumption_amount_zeng_array,$orderGoodsList[$k]['gift_price']);
                }
                $shopRefundOrderGoodsModel = new ShopRefundOrderGoods();
                $res =  $shopRefundOrderGoodsModel->saveAll($orderGoodsList);



                // 添加操作记录
                $content = '创建退款订单：【'. $operator_name . '】创建了【' . $request['consignee'] . '】' . '的订单，退款订单号：【' . $data['refund_order_no'] . '】';

                $code = $data;

                $code['orderGoodsList']  = $orderGoodsList;

                // 需要放开
                $this->addActionRecord($request['operator_id'],'shop_refund_order_create',$order->id,$content,'shop','refund',json_encode($code));
                if($is_pay == '1'){

                    $customer_id   = $data['uid'];    // 客户的id
                    // 处理客户的余额
                    $customerModel = new \app\crm\model\Customer();

                    $balanceData   = [                // 余额变更数据集
                        'change_type'  => $data['type'] == 1?2:1,      // 变动类型 1:增加 2:减少
                        'change_balance' => $pay_amount,  //变更的本金
                        'change_gift_balance' => $gift_amount, //变更的赠金
                    ];

                    //订单信息
                    $orderInfo = [
                        'shop_id'=>$data['shop_id'],
                        'customer_id'=>$customer_id,
                        'order_type' => $data['type'],
                        'order_id'=>$order->id,
                        'order_no'=>$data['refund_order_no'],
                        'type'=>$data['type'],
                        'refund_type' => $data['refund_type'],
                        'is_pay'=>$data['is_pay']
                    ];
                    switch ($data['type']){
                        case 1:
                            $orderInfo['notes'] = 705;
                            $orderInfo['remarks'] = '退款';
                            break;
                        case 3:
                            $orderInfo['notes'] = 703;
                            $orderInfo['remarks'] = '收款';
                            break;
                    }

                    $newOrderData  = [   // 新单变更数据集
                        'cj_time'  => $data['deal_time'],// 成交时间-时间戳
                        'cj_money'    => $pay_amount,     // 成交金额
                        'cj_order_id' => $order->id,     // 成交的订单单号
                    ];

                    // 处理客户的余额
                    if($data['api_type'] == 0) {
                        $customerModel->processingFunds($customer_id,$balanceData,$data['deal_time'],$newOrderData,$orderInfo);
                    }

                    // 记录最新消费时间
                    $addLogModel = new AddOrderLog();
                    $addLogModel->addData($customer_id,$orderInfo['shop_id'],$orderInfo['order_no'],$data['deal_time'],$orderInfo['order_type']);


                    // 金蝶推送云星空订单  //
                    $this->sendYxk($customer_id,$data['type'],$order->id);
                    Db::commit();

                    /************************开始发短信******************/

                    $xh_bj= array_sum($consumption_amount_bj_array);  //消耗本金（本金+店转）
                    $xh_zj = array_sum($consumption_amount_zeng_array); //消耗赠金

                    $consumption_amount = bcadd($xh_zj,$xh_bj,2); //消费金额（本金+赠金+店转）


                    if($consumption_amount >0 && $data['refund_type'] != '101.03'){
                        $shop_id = $orderInfo['shop_id'];
                        $shopinfo = Db::name('shop')->where('shop_id',$shop_id)->field('shop_name,city_name,market_id')->find();
                        $customerData  = DB::name('customer')->where('id',$customer_id)->field('telephone,is_show_balance,customer_name')->find();

                        $is_send_msgtemplate = $this->is_send_msgtemplate($customerData['telephone']);

                        $shopName = $shopinfo['shop_name'];

                        if(!empty($is_send_msgtemplate)){
                            //推送公众号
                            $order_no = $data['refund_order_no']; //订单号

                            $time = date('Y-m-d h:i:s',$time); //支付时间
                            switch ($request['type']){
                                case 1:
                                    //退款
                                    $sendData = [
                                        'open_id'=>$is_send_msgtemplate,
                                        'data'=>[
                                            'character_string1'=>['value'=>$order_no],
                                            'time4'=>['value'=>$time],
                                            'const6'=>['value'=>'现金退款'],
                                            'thing5'=>['value'=>$shopName],
                                            'amount2'=>['value'=>$consumption_amount]
                                        ]
                                    ];
                                    break;
                                case 3:
                                    //收款
                                    $sendData = [
                                        'open_id'=>$is_send_msgtemplate,
                                        'data'=>[
                                            'character_string4'=>['value'=>$order_no],
                                            'time2'=>['value'=>$time],
                                            'thing10'=>['value'=>$customerData['customer_name']],
                                            'thing3'=>['value'=>$shopName],
                                            'amount1'=>['value'=>$consumption_amount]
                                        ]
                                    ];
                                    break;
                            }

                            $this->send_msg($request['type'],$sendData);


                        }else{
                            //发短信
                            $is_send = $customerData['is_show_balance'];
                            $telephone = $customerData['telephone'];

                            $residue_amount = Db::name('customer_account')->where('id', $customer_id)->value('(IFNULL(balance, 0) + IFNULL(gift, 0))'); //消费后剩余余额

                            switch ($request['type']){
                                case 1:
                                    $xh_bj = bcsub(0,$xh_bj,2);
                                    $xh_zj = bcsub(0,$xh_zj,2);
                                    $send_consumption_amount = '本金'.$xh_bj."元，赠金".$xh_zj;
                                    break;

                                case 3:
                                    $send_consumption_amount = '本金'.$xh_bj."元，赠金".$xh_zj;;
                                    break;
                            }
                            $sendData = [
                                'market_id' => $shopinfo['market_id'],
                                'shop_id' => $request['shop_id'],
                                'customer_id' => $customer_id,
                                'telephone' => $telephone,
                                'content' => '【欣奕除疤】尊敬的客户您好，您于'.date('y-m-d H:i',$time).'分 在'.$shopName.'服务中心消费'.$send_consumption_amount.'元，当前余额'.$residue_amount.'元，如有疑问，可致电400-668-8162。拒收请回复R',
                                'type' => 1,
                                'order_id' => $order->id,
                                'order_type' => $request['type'],
                                'expend_money' => $consumption_amount,
                                'surplus_money' => $residue_amount,
                            ];
                            //开始发短信
                            $sendMsg = new SendMsg();
                            $sendMsg->sendSMS($sendData);
                        }
                    }
                    /************************结束发短信******************/



                    // 判断是否已经支付结束
                    $this->error = '创建成功';
                }else{
                    $this->error = '创建成功!';
                }

                if(!empty($request['deal_time']) && $request['deal_time'] != '0000-00-00' && $request['deal_time'] !== date('Y-m-d'))
                {
                    $logData = ['shop_id' => $request['shop_id'],'date' => $request['deal_time'],'create_time' => date('Y-m-d')];
                    Db::name('shop_retention_log')->insert($logData);
                }


                return true;
            }

        } catch (\Exception $e) {

            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
        $this->error = '创建失败';
        return false;
    }



    //订单推送至运行空
    public function sendYxk($customer_id,$type,$order_id){

        $customerModel = new \app\crm\model\Customer();
        $customerInfo = DB::name('customer')->where('id',$customer_id)->field('fcustId,king_no')->find();
        if(empty($customerInfo['fcustId']) && empty($customerInfo['king_no'])){
            // 金蝶推送云星空订单  //
            $res = $customerModel->pushKingCustomer($customer_id);
            if ($res == false) {
                throw new \Exception($customerModel->getError());
            }
        }
        $kingDee = new Kingdee();
        switch($type){
            case 1:
                //退款单
                $result=$kingDee->refund_money($order_id);
                break;
            case 2:
                //退货单
                $result=$kingDee->refund_goods($order_id);
                break;
            case 3:
                //收款单
                $result=$kingDee->receipt_money($order_id);
                break;
            case 4:
                //出货单
                $result=$kingDee->send_order($order_id);
                break;
            case 5:
                //出货出库单、核销记录出库单
                $result=$kingDee->send_service_prestock_order($order_id);
                break;
            case 6:
                //出货出库单、核销记录出库单
                $result=$kingDee->send_case_order($order_id);
                break;
        }

        if ($result['code']) {
            throw new \Exception($result['msg']);
        }
        return true;
    }






    //判断客户是发短信还是发微信消息推送
    public function is_send_msgtemplate($phone){
        $openid = '';
        $unionId = DB::name('mini_program_fans')->where('telephone',$phone)->value('unionId');
        if(!empty($unionId)){
            $openid = DB::name('wx_gzh_fans')->where('unionid',$unionId)->value('openid');
        }

        // 查询中台系统是否关注
        if(empty($openid))
        {
            $fans_url = env('SHOP.crm_url').'/crm/ApiShop/crmGzhFans?phone='.$phone;
            $fans_apiResponse = $this->callApi($fans_url);
            if ($fans_apiResponse)
            {
                $fans_data = json_decode($fans_apiResponse, true);
                if($fans_data['code'] == 200)
                {
                    $openid = $fans_data['data'];
                }
            }
        }

        return $openid;
    }

    public function send_msg($ordertype,$data){
        switch ($ordertype){
            case 1:
                //退款单
                $template_id = 'UTPpdzIyVe-GIN69PnuRzDXpo-MYDgDpitBfQPWKt18';
                break;

            case 2:
                //退货单
                $template_id = 'dCfi6iKkaszcYF3WoIZ-rzvJM4Bnh2n1kAfc8FhOXlc';
                break;
            case 3:
                //收款单
                $template_id = '-WYqE4OtQ07sxXa3RNwg8dnmKpKIM5ykX1cDGBtsACA';
                break;
            case 4:
                //出货单
                $template_id = 'dCfi6iKkaszcYF3WoIZ-rzvJM4Bnh2n1kAfc8FhOXlc';
                break;
        }
        $data['template_id'] = $template_id;
        $data['miniprogram'] =[
            'app_id'=>'',
            'pagepath'=>''
        ];
        $data['url']='';
        $sendModel = new SendMsgModel();
        $sendModel->wx_send_msgtemplate($data);
    }


    /*
    *  作废核销/订单可操作时间
    * $dael_time -订单的成交日期
    */
    public function orderVerfiy($day,$deal_time){
        $orderVerfiy =$this->orderOperableTime($day);

        if(count($orderVerfiy) == 1){
            $monthOneDay = strtotime(date('y-m-01'));
            $monthLastDay = strtotime(date('y-m-t 23:59:59'));
            if(!($deal_time<=$monthLastDay && $monthOneDay<=$deal_time)){
                return false;
            }
        }else{
            $begin_time_str = $orderVerfiy[1]['year'].'-'.$orderVerfiy[1]['month'].'-01';
            $end_time_str = $orderVerfiy[0]['year'].'-'.$orderVerfiy[0]['month'].'-t 23:59:59';

            $monthOneDay = strtotime(date($begin_time_str));
            $monthLastDay = strtotime(date($end_time_str));

            if(!($deal_time<=$monthLastDay && $monthOneDay<=$deal_time)){
                return false;
            }
        }
        return true;
    }

    //创建-修改-作废-只允许在当月的15号之前操作-获取订单可操作时间
    public function orderOperableTime($day){

        $today = new \DateTime();
        $currentDay = (int)$today->format('d');
        $currentMonth = (int)$today->format('n');
        $currentYear = (int)$today->format('Y');
        $allowableMonths = [];

        // 如果当前日期是15号或之前，允许创建上月和本月的订单
        if ($currentDay <= $day) {
            // 添加本月
            $allowableMonths[] = [
                'year' => $currentYear,
                'month' => $currentMonth
            ];

            // 计算上月（处理跨年情况）
            $lastMonth = $currentMonth - 1;
            $lastMonthYear = $currentYear;

            if ($lastMonth === 0) {
                $lastMonth = 12;
                $lastMonthYear--;
            }
            // 添加上月
            $allowableMonths[] = [
                'year' => $lastMonthYear,
                'month' => $lastMonth
            ];
        }
        // 否则（15号之后），只能创建本月的订单
        else {
            $allowableMonths[] = [
                'year' => $currentYear,
                'month' => $currentMonth
            ];
        }
        return $allowableMonths;
    }

    //获取
    public function customerBalanceVerify($customer_id){

        $balance = CustomerAccount::where('id',$customer_id)->find();
        if(empty($balance)){
            throw new \Exception("客户余额数据异常");
        }
        $benj = $balance['balance']; //顾客剩余的本金
        $zengj = $balance['gift'];   //顾客剩余的赠金

        $customerMoney = bcadd($benj,$zengj,2);
        if($customerMoney<0){
            throw new \Exception('客户余额为负,无法下单');
        }
        return [$benj,$zengj,$customerMoney];
    }



    /**
     * 创建退货单
     * @param  array $request 请求参数
     * @return bool
     * @author LIU
     * @create 2021-10-25
     */
    public function addGoodsData($request)
    {

        try {
            $validate = new \app\shop\validate\Refund();
            if (!$validate->scene('createGoods')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }

        }catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }

        //检查订单是否已经录入
        if(!empty($request['api_order_id']))
        {
            $check_count = Db::name('shop_refund_order')->where('type',2)->where('api_order_id',$request['api_order_id'])->count();
            if($check_count > 0)
            {
                $this->error = '此商城订单已经录入';
                return false;
            }
        }

        Db::startTrans();
        try {
            $deal_time = strtotime($request['deal_time']); //成交时间
            $orderVerfiy = $this->orderVerfiy(5,$deal_time);
            if(!$orderVerfiy){
                throw new \Exception('订单不可创建');
            }
            $time = time();
            $orderDataList = $request['goodsList'];
            $goods_price= [];
            $payAmount = [];

            $uid = trim($request['uid']);
            $customer = Customer::with(['info'=>function($query)use($uid){
                $query->field('id,type_store');
            }])->where('id',$uid)->find();
            if($customer['info']['type_store'] == 4){
                throw new \Exception('无法创建订单');
            }


            $shop = ShopModel::where('shop_id',$request['shop_id'])->lock(true)
                ->field('shop_name,market_id,market_name,type,keycode')
                ->find();
            /**************计算实退货本金/赠金*****************/
            $refund_bj = $refund_zj  = 0;
            $refund_bj_arr = $refund_zj_arr  = [];
            $project_ids = $product_ids =  [];

            foreach ($orderDataList as $key => $val) {
                if (!isset($val['descs']) || empty($val['descs'])) {
                    throw new \Exception('退款备注必填');
                }
                if (!isset($val['number']) || empty($val['number'])) {
                    throw new \Exception('退货数量必须填写');
                }
                if (!isset($val['house_code']) || empty($val['house_code'])) {
                    throw new \Exception('退款仓库必须选择');
                }

                if($val['goods_type'] == 1){
                    array_push($project_ids,$val['id']);
                }else{
                    array_push($product_ids,$val['id']);
                }

                $payAmount[] = bcmul(abs($val['pay_price']), $val['number'], 2);
                $goods_price[] = bcmul($val['goods_price'], $val['number'], 2);

                array_push($refund_bj_arr,$val['refund_principal_price']); //退款本金
                array_push($refund_zj_arr,$val['gift_price']);  //退款赠金

                if($val['prestock_type'] == 1){
                    $refund_total = 0;
                    $refund_goods_total = 0;
                    $prestock_all_refund_total = [];
                    $prestock_all_goods_total = [];

                    if(!empty($val['prestock'])){
                        foreach($val['prestock'] as $k=>$v){
                            array_push($prestock_all_refund_total,bcmul($v['shipment_num'] ,$v['pay_price'],2));
                            array_push($prestock_all_goods_total,bcmul($v['shipment_num'] ,$v['goods_price'],2));
                            $prestockGoods = CustomerPrestockGoods::with(['shopordergoods'=>function($query)use($prestock_all_goods_total){
                                $query->field('id,pay_amount,gift_amount,shop_transfer_amount,number,pay_price');
                            }])->where('id',$v['c_prestock_goods_id'])->field('business_type,id,order_goods_id')->find();
                            $order_num = $prestockGoods['shopordergoods']['number'];
                            $single_consumption_bj = bcdiv($prestockGoods['shopordergoods']['pay_amount'],$order_num,2);
                            $single_consumption_zj = bcdiv($prestockGoods['shopordergoods']['gift_amount'],$order_num,2);
                            $tui_zj = $tui_bj = 0;
                            $tui_zj = bcmul($single_consumption_zj,$v['shipment_num'],2); //退货赠金
                            $tui_bj =  bcmul($single_consumption_bj,$v['shipment_num'],2); //退货本金

                            $sj_thzk = bcadd(0,array_sum([$tui_zj, $tui_bj]),2);
                            $thzk = bcmul($prestockGoods['shopordergoods']['pay_price'],$v['shipment_num'],2);
                            if($sj_thzk!= $thzk){
                                $tui_bj =  bcsub($thzk,$tui_zj,2); //退货本金
                            }
                            array_push($refund_bj_arr,$tui_bj);
                            array_push($refund_zj_arr,$tui_zj);

                        }
                    }
                    $refund_total = array_sum($prestock_all_refund_total);
                    $payAmount[] = $refund_total;
                    $refund_goods_total = array_sum($prestock_all_goods_total);
                    $goods_price[] = $refund_goods_total;
                }

            }

            $api_type = $request['api_type'] ?? 0;
            //如果是商城 直接获取金额
            if($api_type != 0) {
                $reality_refund_total = $request['total_amount'];
                $refund_bj = $request['total_amount'];
                $refund_zj = 0;
            }
            else {
                $refund_bj = bcadd(0,array_sum($refund_bj_arr),2); //实际退货款本金
                $refund_zj = bcadd(0,array_sum($refund_zj_arr),2); //实际退货款赠金
                $reality_refund_total  = bcadd($refund_bj,$refund_zj,2);//实际退货总款
            }
            //订单品项信息
            $projectItem = [];
            if(!empty($project_ids)){
                $projectItem = ProductItem::whereIn('id',$project_ids)->column('name,product_info,unit_code,unit_name,kingdee_code,standard_price','id');
            }

            //订单商品信息
            $product = [];
            if(!empty($product_ids)){
                $product = ShopGoods::whereIn('id',$product_ids)->column('name,category_id,kingdee_code,goods_price,spec_name,unit_code,unit_name','id');
            }


            $goods_price = array_sum($goods_price);
            $operator_name= AdminUser::where(['id' => $request['operator_id']])->value('realname');

            // 验证

            $data = [
                'uid'               => trim($request['uid']), // 客户
                'source_id'         => $customer['source_id'],
                'consignee'         => trim($customer['customer_name']), // 收货人
                'refund_order_no'   => $this->getOrderNo(), // 订单号
                'shop_id'           => $request['shop_id'], // 门店id
                'shop_name'         => trim($shop['shop_name']), // 门店名称
                'operator_id'       => $request['operator_id'],//制单员id
                'operator_name'     => $operator_name,//制单员姓名
                'create_time'       => $time, // 创建时间
                'deal_time'         => strtotime($request['deal_time']), // 成交日期
                'goods_price'       => $goods_price, // 订单标准金额
                'total_amount'      => $reality_refund_total, // 实退金额
                'gift_amount'       => $refund_zj,  // 实退赠金
                'pay_amount'        => $refund_bj,   // 实退本金
                'description'            => isset($request['description']) ? $request['description'] : '', // 订单描述
                'order_type'             => $customer['info']['type_store']??'', // 订单类型 1新单 2补单
                'project_type'           => isset($request['project_type']) ? $request['project_type'] : 0, // 订单类型
                'income_type'            => '', // 收入类型 1 服务（各类疗程卡项及疗程卡项赠送产品）2 产品销售（单独付费购买产品）3 医美收入
                'sales_policy'           => '', // 销售政策编码
                'type'               => 2,     //退款单类型 1退款单 2退货单
                'market_id'          => $shop['market_id'],   // 市场id
                'market_name'        => $shop['market_name'], // 市场名称
                'sales_organization'       => isset($request['sales_organization']) ? $request['sales_organization'] : 0, // 销售组织编码
                'sales_name'         => isset($request['sales_name']) ? $request['sales_name'] : '', // 销售组织名称
                'settlement_organization'  => isset($request['settlement_organization']) ? $request['settlement_organization'] : 0, // 结算组织编码
                'settlement_name'     => isset($request['settlement_name']) ? $request['settlement_name'] : '', // 结算组织名称
                'sale_id'             => $request['sale_id'], // 销售员id
                'sale_name'           => trim($request['sale_name']), // 销售员姓名
                'delivery_name'       => isset($request['delivery_name']) ? $request['delivery_name'] : '', // 库存部门名称
                'delivery_king'       => isset($request['delivery_king']) ? $request['delivery_king'] : '', // 库存部门编码
                'api_type' => $request['api_type'] ?? 0, //0中台系统 1商城积分兑换订单 2商城普通订单
                'api_order_id' => $request['api_order_id'] ?? '', //商城订单ID
            ];
            $order = $this->create($data);
            if ($order) {
                $service_ids_arr = [];
                // 处理客户的余额 //
                $deduct_balance = $deduct_gift = [];
                $orderGoodsList = $refund_prestock_insert_all = [];
                foreach ($orderDataList as $k => $v) {
                    $order_goods = [];
                    if ($v['prestock_type'] == 1 && !empty($v['prestock'])) {
                        foreach ($v['prestock'] as $kk => $vv) {

                            $prestockGoods = CustomerPrestockGoods::with(
                                ['shopordergoods' => function ($query) use ($orderGoodsList) {
                                    $query->field('id,pay_price,pay_amount,gift_amount,shop_transfer_amount,number,kingdee_code,goods_price,spec_name,unit_code,is_gift,house_code,is_project,house_code_name,goods_alias_name,data_business_two_type,data_business_type,takeout_stock_num');
                                }])->where('id', $vv['c_prestock_goods_id'])
                                ->field('business_type,id,order_goods_id,goods_id')->find();

                            if (!empty($prestockGoods) && $vv['shipment_num'] > 0) {
                                $order_num = $prestockGoods['shopordergoods']['number'];
                                $single_consumption_bj = bcdiv($prestockGoods['shopordergoods']['pay_amount'], $order_num, 2);
                                $single_consumption_zj = bcdiv($prestockGoods['shopordergoods']['gift_amount'], $order_num, 2);

                                $order_goods['data_business_type'] = $prestockGoods['shopordergoods']['data_business_type'];
                                $order_goods['data_business_two_type'] = $prestockGoods['shopordergoods']['data_business_two_type'];
                                $order_goods['order_id'] = $order->id;
                                $order_goods['create_time'] = $time;
                                $order_goods['goods_id'] = $prestockGoods['goods_id'];
                                $order_goods['goods_name'] = $vv['goods_name'];
                                $order_goods['kingdee_code'] = $prestockGoods['shopordergoods']['kingdee_code'];
                                $order_goods['goods_price'] = $prestockGoods['shopordergoods']['goods_price'];
                                $order_goods['pay_price'] = $prestockGoods['shopordergoods']['pay_price'];
                                $order_goods['spec_name'] = $prestockGoods['shopordergoods']['spec_name'];
                                $order_goods['unit_code'] = $prestockGoods['shopordergoods']['unit_code'];
                                $order_goods['number'] = $vv['shipment_num'];
                                $order_goods['descs'] = '退预存货';
                                $order_goods['goods_deal_time'] = $time;
                                $order_goods['is_gift'] = $prestockGoods['shopordergoods']['is_gift'];
                                $order_goods['house_code'] = $prestockGoods['shopordergoods']['house_code'];
                                $order_goods['is_project'] = $prestockGoods['shopordergoods']['is_project'];//是否服务 1 否 2是
                                $order_goods['house_code_name'] = $prestockGoods['shopordergoods']['house_code_name'];
                                $order_goods['goods_alias_name'] = $prestockGoods['shopordergoods']['goods_alias_name'];
                                $order_goods['is_prestock'] = 1;
                                $order_goods['takeout_stock_num'] = $vv['shipment_num'];
                                $order_goods['gift_price'] = bcmul($single_consumption_zj, $vv['shipment_num'], 2); //退货赠金
                                $order_goods['refund_principal_price'] = bcmul($single_consumption_bj, $vv['shipment_num'], 2); //退货本金

                                $sj_thzk = bcadd(0, array_sum([$order_goods['gift_price'], $order_goods['refund_principal_price']]), 2);
                                $thzk = bcmul($order_goods['pay_price'], $vv['shipment_num'], 2);
                                if ($sj_thzk != $thzk) {
                                    $sj_tui_zj_dz = bcadd($order_goods['shop_transfer_price'], $order_goods['gift_price'], 2);
                                    $order_goods['refund_principal_price'] = bcsub($thzk, $sj_tui_zj_dz, 2); //退货本金
                                }

                                $refund_order_goods_id = Db::name('shop_refund_order_goods')->insertGetId($order_goods);
                                //生成预存货退货变更记录
                                $refund_prestock_insert['operator_id'] = $request['operator_id'];
                                $refund_prestock_insert['create_time'] = $time;
                                $refund_prestock_insert['c_prestock_goods_id'] = $vv['c_prestock_goods_id'];
                                $refund_prestock_insert['shop_order_id'] = $order->id;
                                $refund_prestock_insert['shop_order_goods_id'] = $refund_order_goods_id;
                                $refund_prestock_insert['shop_id'] = $data['shop_id'];
                                $refund_prestock_insert['customer_id'] = $data['uid'];
                                $refund_prestock_insert['num'] = $vv['shipment_num'];
                                $refund_prestock_insert['type'] = 2;
                                $refund_prestock_insert['remark'] = '预存货退货';
                                array_push($refund_prestock_insert_all, $refund_prestock_insert);
                                //对预存货数量进行修改

                                $prestockGoods->num = bcsub($prestockGoods['shopordergoods']['takeout_stock_num'], $vv['shipment_num'], 2);
                                $prestockGoods->update_time = time();
                                $prestockGoods->save();
                            }
                        }
                    }
                    else {

                        $order_goods['data_business_type'] = $v['business_type'];
                        $order_goods['data_business_two_type'] = 0;
                        $order_goods['order_id'] = $order->id;
                        $order_goods['create_time'] = $time;
                        $order_goods['is_gift'] = isset($v['is_gift']) ? $v['is_gift'] : 0;
                        $order_goods['goods_alias_name'] = isset($v['goods_alias_name']) ? $v['goods_alias_name'] : '';
                        $order_goods['goods_deal_time'] = isset($v['goods_deal_time']) ? strtotime($v['goods_deal_time']) : 0;
                        $order_goods['house_code_name'] = isset($v['house_code_name']) ? $v['house_code_name'] : '';
                        $order_goods['number'] = $v['number'];
                        $order_goods['descs'] = $v['descs'];
                        $order_goods['refund_service_ids'] = '';
                        $order_goods['pay_price'] = bcdiv(bcadd($v['refund_principal_price'], $v['gift_price'], 2), $v['number'], 2);
                        $order_goods['house_code'] = $v['house_code'];
                        $order_goods['gift_price'] = $v['gift_price'];
                        $order_goods['refund_principal_price'] = $v['refund_principal_price'];
                        $order_goods['service_goods_str'] = '';
                        if ($v['goods_type'] == 2) {
                            //商品
                            $order_goods['is_project'] = 1;//是否服务 1 否 2是
                            $order_goods['kingdee_code'] = $product[$v['id']]['kingdee_code'] ?? '';
                            $order_goods['goods_price'] = $product[$v['id']]['goods_price'] ?? 0.00;
                            $order_goods['spec_name'] = $product[$v['id']]['spec_name'] ?? '';
                            $order_goods['unit_code'] = $product[$v['id']]['unit_code'] ?? '';
                            $order_goods['unit_name'] = $product[$v['id']]['unit_name'] ?? '';
                            $order_goods['goods_name'] = $product[$v['id']]['name'] ?? '';
                        } else {

                            //品项
                            $order_goods['is_project'] = 2;//是否服务 1 否 2是
                            $order_goods['kingdee_code'] = $projectItem[$v['id']]['kingdee_code'] ?? '';
                            $order_goods['goods_price'] = $projectItem[$v['id']]['price'] ?? 0.00;
                            $order_goods['spec_name'] = $projectItem[$v['id']]['spec_name'] ?? '';
                            $order_goods['unit_code'] = $projectItem[$v['id']]['unit_code'] ?? '';
                            $order_goods['unit_name'] = $projectItem[$v['id']]['unit_name'] ?? '';
                            $order_goods['goods_name'] = $projectItem[$v['id']]['name'] ?? '';

                            $order_goods['service_goods_str'] = isset($projectItem[$v['id']]) ? $projectItem[$v['id']]['product_info'] : '';

                            if (!empty($v['service'])) {
                                $service_ids = [];
                                foreach ($v['service'] as $kk => $vv) {
                                    array_push($service_ids, $vv['id']);
                                    array_push($service_ids_arr, $vv['id']); //作废卡项使用
                                }
                                $order_goods['refund_service_ids'] = implode(',', $service_ids);
                            }
                        }
                        array_push($orderGoodsList, $order_goods);
                    }
                }

                if (!empty($refund_prestock_insert_all)) {
                    $customerPrestockExitModel = new CustomerPrestockExit();
                    $customerPrestockExitModel->saveAll($refund_prestock_insert_all);
                }

                if (!empty($orderGoodsList)) {
                    $shopRefundOrderGoods = new ShopRefundOrderGoods();
                    $shopRefundOrderGoods->saveAll($orderGoodsList);
                }
                //如有卡项，卡项作废
                if (!empty($service_ids_arr)) {
                    Service::whereIn('id', $service_ids_arr)->update(['status' => 3]);
                }

                $customerModel = new \app\crm\model\Customer();
                $customer_id = $data['uid'];    // 客户的id
                $balanceData = [                // 余额变更数据集
                    'change_type' => 1,      // 变动类型 1:增加 2:减少
                    'change_balance' => $refund_bj,
                    'change_gift_balance' => $refund_zj,
                ];
                $orderInfo = [
                    'customer_id' => $customer_id,
                    'order_id' => $order->id,
                    'type' => 2,
                    'notes' => 709,
                    'remarks' => '退货'
                ];
                // 处理客户的余额 //
                $customerModel->processingFunds($customer_id, $balanceData, $request['deal_time'], [], $orderInfo);
                // 金蝶推送云星空订单  //
                $this->sendYxk($customer_id,2,$order->id);
                Db::commit();
                /******************给顾客发短信 -仅限川渝市场-start************/
                $consumption_amount = $reality_refund_total; //消费金额


                $shop_id = $request['shop_id'];
                $shopinfo = Db::name('shop')->where('shop_id',$shop_id)->field('shop_name,city_name,market_id')->find();
                if($consumption_amount > 0) {
                    $shopName = $shopinfo['shop_name'];
                    $customerInfo = DB::name('customer')->where('id',$customer_id)->field('telephone,is_show_balance,customer_name')->find();

                    $telephone = $customerInfo['telephone'];
                    $customer_name = $customerInfo['customer_name'];
                    $consumption_amount = bcsub(0,$consumption_amount,2); //发短信、消息模板使用
                    $open_id = $this->is_send_msgtemplate($telephone);
                    if(!empty($open_id)){
                        //推送公众号
                        $time = date('Y-m-d h:i:s',$time); //创建订单时间
                        //退货
                        $sendData = [
                            'open_id'=>$open_id,
                            'data'=>[
                                'thing1'=>['value'=>$shopName],
                                'time5'=>['value'=>$time],
                                'amount3'=>['value'=>$consumption_amount],
                                'thing12'=>['value'=>$customer_name],
                            ]
                        ];
                        $this->send_msg(2,$sendData);
                    }else{
                        $residue_amount = Db::name('customer_account')->where('id', $customer_id)->value('(IFNULL(balance, 0) + IFNULL(gift, 0))'); //消费后剩余余额
                        $sendData = [
                            'market_id' => $shopinfo['market_id'],
                            'shop_id' => $request['shop_id'],
                            'customer_id' => $customer_id,
                            'telephone' => $telephone,
                            'content' => '【欣奕除疤】尊敬的客户您好，您于'.date('y-m-d H:i',$time).'分 在'.$shopName.'服务中心消费'.$consumption_amount.'元，当前余额'.$residue_amount.'元，如有疑问，可致电400-668-8162。拒收请回复R',
                            'type' => 1,
                            'order_id' => $order->id,
                            'order_type' => $request['type'],
                            'expend_money' => $consumption_amount,
                            'surplus_money' => $residue_amount,
                        ];
                        //开始发短信
                        $sendMsg = new SendMsg();
                        $sendMsg->sendSMS($sendData);
                    }
                }


                if (!empty($request['deal_time']) && $request['deal_time'] != '0000-00-00' && $request['deal_time'] !== date('Y-m-d')) {
                    $logData = ['shop_id' => $request['shop_id'], 'date' => $request['deal_time'], 'create_time' => date('Y-m-d')];
                    Db::name('shop_retention_log')->insert($logData);
                }

                $this->error = '创建成功';
                return true;
            }

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '创建失败';

        return false;

    }





    /**

     * 修改订单基本信息

     * @param array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-03

     */

    public function saveData($request)

    {

        // 验证

        try{

            $validate = new \app\shop\validate\Refund();

            if (!$validate->scene('update')->check($request)) {

                $this->error = $validate->getError();

                return false;

            }

        }catch(\Exception $e){

            $this->error =$e->getMessage();

            return false;

        }

        $id = $request['order_id'] ?? 0;

        if (!$id) {

            $this->error = '参数错误';

            return false;

        }



        $order = Db::name('shop_refund_order')->where('id',$id)->find();

        if(!$order)

        {

            $this->error = '订单不存在';

            return false;

        }

        if($order['status'])

        {

            $this->error = '订单当前不可修改';

            return false;

        }



        try {

            $time = time();

            $data = [

                'house_id'     => isset($request['house_id']) ? trim($request['house_id']) : '', // 仓库

                'consignee'    => isset($request['consignee']) ? trim($request['consignee']) : '', // 收货人

                'mobile'       => isset($request['mobile']) ? trim($request['mobile']) : '', // 收货人手机号

                'province'     => isset($request['province']) ? trim($request['province']) : '', // 省

                'city'         => isset($request['city']) ? trim($request['city']) : '', // 市

                'district'     => isset($request['district']) ? trim($request['district']) : '', // 区

                'address'      => isset($request['address']) ? trim($request['address']) : '', // 收货地址

                'description'  => isset($request['description']) ? trim($request['description']) : '', // 订单备注

                'update_time'  => $time, // 创建时间

            ];



            $bool = $this->where(['id'=>$id])->update($data);

            if ($bool !== false)

            {

                // 添加操作记录

                $content = '';

                if($order['house_id'] != $data['house_id'])

                {

                    $where = [];

                    $house_ids = [$order['house_id'],$data['house_id']];

                    $where = [

                        ['id','in', $house_ids]

                    ];

                    $house_name = Db::name('shop_warehouse')->where($where)->column('name','id');

                    $content .= '将发货仓库【' . $house_name[$order['house_id']] . '】修改为【' . $house_name[$data['house_id']] . '】；';

                }

                if($order['province'] != $data['province'] || $order['city'] != $data['city'] || $order['district'] != $data['district'])

                {

                    $where = [];

                    $region_ids = [$order['province'],$order['city'],$order['district'],$data['province'],$data['city'],$data['district']];

                    $where = [

                        ['id', 'in', $region_ids]

                    ];

                    $region = Db::name('shop_region')->where($where)->column('name','id');

                    $content .= '将收货地址【' . $region[$order['province']]. $region[$order['city']] .$region[$order['district']] . '】修改为【' . $region[$data['province']] . $region[$data['city']] . $region[$data['district']] . '】；';

                }

                if($order['address'] != $data['address'])

                {

                    $content .= '将详细地址【' . $order['address'] . '】修改为【' . $data['address'] . '】；';

                }

                if($order['consignee'] != $data['consignee'])

                {

                    $content .= '将联系人【' . $order['consignee'] . '】修改为【' . $data['consignee'] . '】；';

                }

                if($order['mobile'] != $data['mobile'])

                {

                    $content .= '将手机号【' . $order['mobile'] . '】修改为【' . $data['mobile'] . '】；';

                }

                if($order['description'] != $data['description'])

                {

                    $content .= '将订单备注【' . $order['description'] . '】修改为【' . $data['description'] . '】；';

                }



                if ($content)

                {

                    $code = json_encode($data);

                    $this->addActionRecord($request['operator_id'], 'shop_refund_order_update', $id, $content, 'shop', 'order', $code);

                }



                $this->error = '更新成功';

                return true;

            }

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '更新失败';

        return false;

    }



    /**

     * 修改订单商品

     * @param  array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-05

     */

    public function saveOrderGoodsData($request)

    {

        try {

            $order_id = $request['order_id'] ?? 0; // 订单id

            $opType = $request['op_type'] ?? 0; // 操作类型 1-增加商品 2-修改商品 3-删除商品

            if (!$order_id || !$opType) {

                $this->error = '参数错误';

                return false;

            }

            $order = Db::name('shop_refund_order')->where('id',$order_id)->find();

            if(!$order)

            {

                $this->error = '订单不存在';

                return false;

            }

            if($order['status'])

            {

                $this->error = '订单当前不能修改';

                return false;

            }

            // 操作成功状态

            $saveBool = false;

            $time = time();

            // 增加商品

            if($opType == 1)

            {

                $orderGoodsListArr = isset($request['goodsList']) && $request['goodsList'] ? $request['goodsList'] : [];



                if(!$orderGoodsListArr)

                {

                    $this->error = '参数错误';

                    return false;

                }



                // 验证商品价格

                $goods_ids = array_column($orderGoodsListArr, 'id');



                // 获取商品价格

                $where = [];

                $where = [

                    ['g.id','in', $goods_ids]

                ];

                $field = 'g.id, gs.price, gs.kingdee_code,gs.small_unit_price';

                $goodsInfo = Db::name('shop_goods')

                    ->alias('g')

                    ->join(['shrimp_shop_goods_sku' =>'gs'],'g.id=gs.goods_id')

                    ->where($where)

                    ->field($field)

                    ->select()->toArray();

                $goodsInfo = array_column($goodsInfo, null, 'id');

                $gwhere = [];

                $gwhere = [

                    ['goods_id','in', $goods_ids],

                    ['customer_id','=',$order['uid']]

                ];

                $goodsPrice = Db::name('shop_goods_price')->where($gwhere)->column('price','goods_id');



                $error = '';

                //判断小包装规格 无需对比价目表

                if(!empty($orderGoodsListArr)){

                    $unitCodeList = array_column($orderGoodsListArr,'unit_code');

                    $unitCodeList && $unitCodeList = Db::name('shop_goods_unit')->where('small_unit_code','in',$unitCodeList)->column('unit_id','small_unit_code');

                }

                foreach ($orderGoodsListArr as $key => $value) {

                    if(!isset($value['number']) || empty($value['number']))

                    {

                        $this->error = '请填写销售数量';

                        return false;

                    }

                    if(!isset($goodsPrice[$value['id']]))

                    {

                        $goodsPrice[$value['id']] = $goodsInfo[$value['id']]['price'];

                    }

                    //判断小包装规格 无需对比价目表

                    if(!isset($unitCodeList[$value['unit_code']])){//大包装

                        if($value['customer_price'] != $goodsPrice[$value['id']])

                        {

                            $error .= '商品【' . $value['name'] . '】价目表价格有变动；';

                        }

                        if($value['price'] != $goodsInfo[$value['id']]['price'])

                        {

                            $error .= '商品【' . $value['name'] . '】价格有变动；';

                        }

                    }else{//小包装

                        if($value['price'] != $goodsInfo[$value['id']]['small_unit_price'])

                        {

                            $error .= '商品【' . $value['name'] . '】价格有变动；';

                        }

                    }

                    if($value['kingdee_code'] != $goodsInfo[$value['id']]['kingdee_code'])

                    {

                        $error .= '商品【' . $value['name'] . '】金蝶编码有变动；';

                    }

                }

                if($error)

                {

                    $this->error = $error;

                    return false;

                }



                foreach ($orderGoodsListArr as $k => $v) {

                    $orderGoodsList[$k]['order_id'] = $order_id;

                    $orderGoodsList[$k]['create_time'] = $time;

                    $orderGoodsList[$k]['goods_id'] = $v['id'];

                    $orderGoodsList[$k]['goods_name'] = $v['name'];

                    $orderGoodsList[$k]['kingdee_code'] = $v['kingdee_code'];

                    $orderGoodsList[$k]['goods_price'] = $v['price'];

                    $orderGoodsList[$k]['pay_price'] = $v['customer_price'];

                    $orderGoodsList[$k]['sku_id'] = $v['sku_id'];

                    $orderGoodsList[$k]['item_id'] = $v['item_id'];

                    $orderGoodsList[$k]['item_name'] = $v['item_name'];

                    $orderGoodsList[$k]['unit_id'] = $v['unit_id'];

                    $orderGoodsList[$k]['unit_name'] = $v['unit_name'];

                    $orderGoodsList[$k]['number'] = $v['number'];

                }



                $bool = Db::name('shop_refund_order_goods')->insertAll($orderGoodsList);

                if($bool !== false)

                {

                    // 添加操作记录

                    $goods_name = array_column($orderGoodsList, 'goods_name');

                    $goods_name_str = implode('|', $goods_name);

                    $content = '添加订单商品：【' . $goods_name_str . '】';

                    $code = [];

                    $code['order_id'] = $order_id;

                    $code['orderGoodsList']  = $orderGoodsList;

                    $this->addActionRecord($request['operator_id'],'shop_refund_order_goods',$order_id,$content,'shop','order',json_encode($code));



                    $this->error = '添加订单商品成功';



                    $saveBool = true;

                }

            }

            // 修改商品

            elseif($opType == 2)

            {

                $order_goods_id = isset($request['order_goods_id']) && $request['order_goods_id'] ? $request['order_goods_id'] : '';

                $number = isset($request['number']) && $request['number'] ? $request['number'] : '';

                if (!$order_goods_id || !$number) {

                    $this->error = '参数错误';

                    return false;

                }



                $orderGoods = Db::name('shop_refund_order_goods')->where('id',$order_goods_id)->find();

                if(!$orderGoods)

                {

                    $this->error = '订单商品不存在';

                    return false;

                }



                if(!isset($request['number']) || empty($request['number']))

                {

                    $this->error = '请填写销售数量';

                    return false;

                }



                $goodsData = [

                    'number'     => isset($request['number']) ? trim($request['number']) : 1, // 商品数量

                ];



                $bool = Db::name('shop_refund_order_goods')->where(['id'=>$order_goods_id])->update($goodsData);

                if ($bool !== false) {

                    // 添加操作记录

                    $content = '将商品【' . $orderGoods['goods_name'] . '】数量【' . $orderGoods['number'] . '】修改为【' . $number . '】';

                    $this->addActionRecord($request['operator_id'],'shop_refund_order_goods',$order_id,$content,'shop','order',json_encode($orderGoods));



                    $this->error = '更新订单商品成功';



                    $saveBool = true;

                }

            }

            elseif($opType == 3)

            {

                $order_goods_id = isset($request['order_goods_id']) && $request['order_goods_id'] ? $request['order_goods_id'] : '';

                if (!$order_goods_id) {

                    $this->error = '参数错误';

                    return false;

                }



                $orderGoods = Db::name('shop_refund_order_goods')->where('id',$order_goods_id)->find();

                if(!$orderGoods)

                {

                    $this->error = '订单商品不存在';

                    return false;

                }



                $orderCount = Db::name('shop_refund_order_goods')->where('order_id',$orderGoods['order_id'])->count();

                if($orderCount == 1)

                {

                    $this->error = '订单中至少保留一个有效商品';

                    return false;

                }



                $bool = Db::name('shop_refund_order_goods')->where(['id'=>$order_goods_id])->delete();

                if ($bool !== false) {

                    // 添加操作记录

                    $content = '将商品【' . $orderGoods['goods_name'] . '】删除';

                    $this->addActionRecord($request['operator_id'],'shop_refund_order_goods',$order_id,$content,'shop','order',json_encode($orderGoods));



                    $this->error = '删除订单商品成功';



                    $saveBool = true;

                }

            }



            if ($saveBool) {

                // 更新订单金额

                $payMount   = Db::name('shop_refund_order_goods')->where('order_id', '=', $order_id)->sum('pay_price*number');

                $updateData = [

                    'order_amount' => $payMount,

                    'pay_amount'   => $payMount,

                    'update_time'  => time()

                ];

                $this->where('id', '=', $order_id)->update($updateData);

                return true;

            }

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '操作失败';

        return false;

    }



    /**

     * 修改订单状态
     * 审核、反审核、作废、确认收货
     * @param array $request 请求参数
     * @return bool
     * @author SL
     * @create 2021-06-08
     */

    public function checkOrderData($request)
    {

        Db::startTrans();
        try {
            $is_cancel = $request['is_cancel'] ?? 0;
            $id = $request['order_id'] ?? 0;
            $status = $request['status'] ?? 0;
            if (!$id) {
                throw new \Exception('订单标识不合法');
            }
            $order = $this->where('id',$id)->lock(true)->find();
            if(empty($order)) {
                throw new \Exception('订单不存在');
            }
            // 订单作废
            if($status !== 3) {
                throw new \Exception('订单状态不正确');
            }

            $deal_time = date('Y-m-d',$order['deal_time']);

            if($is_cancel=='1'){
                // echo "申请退款";
                if($order['sales_organization'] == $order['settlement_organization']){
                    $shop_id = $order['shop_id'];
                }else{
                    $shop_id = $request['shop_id'];
                }
                $shop = ShopModel::where('shop_id',$shop_id)->find();
                $saveData = [];
                if($order['shanghu_type'] == '1'){ // 公户
                    $saveData['private_key'] = $shop['shop_gonghu_privateKey']; // 密钥
                    $saveData['cusid'] = $shop['shop_gonghu_cusid']; // 商户号
                    $saveData['appid'] = $shop['shop_gonghu_appid']; // 商户appid

                }

                if($order['shanghu_type'] == '2'){ // 私户
                    $saveData['private_key'] = $shop['shop_sihu_privateKey']; // 密钥
                    $saveData['cusid'] = $shop['shop_sihu_cusid']; // 商户号
                    $saveData['appid'] = $shop['shop_sihu_appid']; // 商户appid
                }

                $saveData['pay_amount'] = $order['pay_amount'];
                $saveData['reqsn'] = 'CX_'.$order['refund_order_no'];
                $saveData['refund_order_no'] = $order['refund_order_no'];

                $payModel = new RefundPayModel();
                $res = $payModel->cancel($saveData);
                if($res['retcode'] == 'FAIL'){
                    throw new \Exception($res['retmsg']);
                }
            }

            $order->status = $status; // 订单状态： 订单状态：0.待支付 1.已支付 2.已下推 3.已评价 4.已取消
            $order->update_time = time();
            $bool = $order->save();

			if ($bool !== false) {
                if($order['type']=='3'){
                    if(isset($order['is_pay'])){
                        $is_pay = $order['is_pay'];
                    }else{
                        $is_pay = '3'; // 3代表以前录入的订单;
                    }
                }else{
                    //echo '不是---收款单--进入';echo '<br/>';
                    $is_pay = '1';
                }
//                $arr = [0=>'待退款',1=>'已退款',2=>'已下推',3=>'已作废'];
//                $content = '';
//                $content .= '，状态：【' . $arr[$order['status']] . '】修改为【' . $arr[$status] . '】';

				if($is_pay=='0'){
					$balanceData   = [];
				}else{
                    $refundOrderGoods = DB::name('shop_refund_order_goods')->where('order_id',$order['id'])->select()->toArray();
                    $time = time();
                    $update=[];
                    $update['is_cancel'] = 1;
                    $update['cancel_time'] = $time;
                    $update['cancel_operator_id'] = $request['operator_id'];
                    foreach($refundOrderGoods as $key=>$v){
                        if($v['is_prestock'] == 1){
                            $res = DB::name('customer_prestock_exit')
                                ->where('shop_order_id',$order['id'])
                                ->where('shop_order_goods_id',$v['id'])
                                ->where('type',2)
                                ->update($update);
                            $c_prestock_goods_id = DB::name('customer_prestock_exit')
                                ->where('shop_order_id',$order['id'])
                                ->where('shop_order_goods_id',$v['id'])
                                ->where('type',2)
                                ->field('c_prestock_goods_id,num')->find();
                            $num = DB::name('customer_prestock_goods')->where('id',$c_prestock_goods_id['c_prestock_goods_id'])->value('num');
                            $update = [
                                'num'=>bcadd($num,$c_prestock_goods_id['num'],2),
                                'update_time'=>$time
                            ];
                            $res = DB::name('customer_prestock_goods')
                                ->where('id',$c_prestock_goods_id['c_prestock_goods_id'])
                                ->update($update);
                        }
                    }

                    $type = $order['type'] == 1?1:2;

                    $balanceData   = [                // 余额变更数据集
                        'change_type'  => $type,      // 变动类型 1:增加 2:减少
                        'change_balance'=>$order['pay_amount'],
                        'change_gift_balance'=>$order['gift_amount'],
                    ];
				}
                $customer_id   = $order['uid'];    // 客户的id
				$newOrderData  = [   // 新单变更数据集
					'cj_order_id' => $id, // 成交的订单单号
					'cj_type' => 1, // 成交的订单单号
				];
                $remarks = [
                    1=>'取消退款', 2=>'取消退货', 3=>'取消收款', 4=>'取消出库'
                ];
                $notes = [
                    1=>706, 2=>710, 3=>704, 4=>708
                ];

				//订单信息
                $orderInfo = [
                    'customer_id'=>$customer_id,
                    'order_id'=>$order->id,
                    'type' => $order['type'],
                    'remarks'=>$remarks[$order['type']],
                    'notes'=>$notes[$order['type']],
                    'order_no'=>$order['refund_order_no'],
                ];

                // 处理客户的余额 //
                $customerModel = new \app\crm\model\Customer();
				$customerModel->processingFunds($customer_id,$balanceData,$deal_time,$newOrderData,$orderInfo);

				// 添加操作记录
//				$this->addActionRecord($request['operator_id'], 'shop_refund_order_check', $id, $content, 'shop', 'refund');

                // 修改顾客最新消费时间
                $addLogModel = new AddOrderLog();
                $addLogModel->deletedData($customer_id,$order['refund_order_no']);

                if(!empty($order['deal_time']) && $order['deal_time'] != '0000-00-00' && $order['deal_time'] !== date('Y-m-d'))
                {
                    $logData = ['shop_id' => $order['shop_id'],'date' => date('Y-m-d', $order['deal_time']),'create_time' => date('Y-m-d')];
                    Db::name('shop_retention_log')->insert($logData);
                }

                Db::commit();
				$this->error = '操作成功';
				return true;
			}
        } catch (\Exception $e) {
            Db::rollbcak();
            $this->error = $e->getMessage();
            return false;
        }

        $this->error = '操作失败';

        return false;

    }



    /**

     * 订单设置发货

     * @param array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-08

     */

    public function sendOrderData($request)

    {

        $id = $request['order_id'] ?? 0;

        $king_send_no = $request['king_send_no'] ?? '';

        $king_sale_no = $request['king_sale_no'] ?? '';

        if (!$id || !$king_send_no || !$king_sale_no) {

            $this->error = '参数错误';

            return false;

        }



        $order = Db::name('shop_refund_order')->where('id',$id)->find();

        if(!$order)

        {

            $this->error = '订单不存在';

            return false;

        }



        if($order['status'] != 2)

        {

            $this->error = '订单当前状态不能设置发货';

            return false;

        }



        try {

            $time = time();

            $data = [

                'status'       => 3, // 订单状态：0.待审核 1.已审核,2.已下推,3.已发货,4.已收货,5已完成,6.已作废

                'king_send_no' => trim($request['king_send_no']),

                'king_sale_no'  => trim($request['king_sale_no']),

                'send_time' => $time,

                'update_time'  => $time, // 时间

            ];



            $bool = $this->where(['id'=>$id])->update($data);

            if ($bool !== false) {

                // 添加操作记录

                $logFieldArr = [

                    'king_send_no'    => '金蝶发货通知单号',

                    'king_sale_no'    => '金蝶销售出库单号',

                ];

                $logContentArr = [];

                foreach ($logFieldArr as $key => $val) {

                    if ($data[$key] != $order[$key]) {

                        $logContentArr[] = "'" . $val . "': " . $data[$key];

                    }

                }

                if ($logContentArr) {

                    $logContentStr = implode('.|.', $logContentArr);

                    $logContentStr = '设置发货成功。' . $logContentStr;

                    $this->addActionRecord($request['operator_id'], 'shop_refund_order_send', $id, $logContentStr, 'shop', 'order',json_encode($data));

                }



                $this->error = '设置发货成功';

                return true;

            }

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '设置发货失败';

        return false;

    }





    /**

     * 生成订单号

     * @param  array $request 请求参数

     * @return String

     * @author SL

     * @create 2021-06-03

     */

    public function getOrderNo()

    {

        $order_sn = null;

        // 保证不会有重复订单号存在

        while(true){

            $order_sn = "TK".date('YmdHis').rand(1000,9999); // 订单编号

            $order_sn_count = DB::name('shop_refund_order')->where('refund_order_no', $order_sn)->count();

            if($order_sn_count == 0)

                break;

        }

        return $order_sn;

    }



    /**

     * 添加订单跟进

     * @param  array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-09 10:49

     */

    public function addFollow(array $request): bool

    {

        try {

            $orderId  = $request['order_id'] ?? 0;

            $contentType = $request['content_type'] ?? 0; // 1-联系客户 2-客户反馈 3-支付 4-客户确认 5-业务员确认 6-其他

            $is_confirm = $request['is_confirm'] ?? 0; // 是否确认 0-未确认 1-确认

            if (!$orderId || !$contentType) {

                $this->error = '参数错误';

                return false;

            }

            // 订单详情

            $orderInfo = Db::name('shop_refund_order')->field('status,is_pay')->where('id',$orderId)->find();

            if(($contentType == 3 && $is_confirm == 1 && in_array($orderInfo['status'], [5,6])) || $orderInfo['is_pay'])

            {

                $this->error = '订单当前状态不能添加支付跟进';

                return false;

            }



            $request['obj_id']      = $orderId;

            $request['follow_type'] = 4; // 1-线索 2-客户 3-商机 4-订单



            // 调用添加跟进

            $followModel = new FollowRecord();

            $bool        = $followModel->addData($request);

            if ($bool) {

                if($is_confirm == 1)

                {

                    if($contentType == 3)

                    {

                        $data = [

                            'is_pay' => 1, // 已支付

                            'pay_type' => 1, // 后台跟进,货到付款

                            'pay_time' => time()

                        ];

                        // 待审核

                        if($orderInfo['status'] == 0)

                        {

                            $data['status'] = 1;

                        }

                        // 已收货

                        if($orderInfo['status'] == 4)

                        {

                            $data['complete_time'] = time();

                        }



                    }

                    elseif($contentType == 4)

                    {

                        $data = [

                            'customer_confirm' => 1 // 客户已确认

                        ];

                    }

                    elseif($contentType == 5)

                    {

                        $data = [

                            'admin_user_confirm' => 1 // 客服(业务员)已确认

                        ];

                    }

                    else{



                    }

                    // 更新商机跟进时间

                    $data['update_time'] = time();

                    $this->where(['id' => $orderId])->update($data);

                }



                $this->error = '添加成功';

                return true;

            }



            $this->error = $followModel->getError();

        } catch (\Exception $e) {

            $this->error = '添加失败';

        }



        return false;

    }



    /**

     * 订单跟进列表

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-09 11:21

     */

    public function getOrderFollowList(array $request): array

    {

        $orderId = $request['order_id'] ?? 0;

        if (!$orderId) {

            $this->error = '参数错误';

            return [];

        }



        $request['map'] = [

            ['field' => 'obj_id', 'value' => $orderId, 'type' => '='],

            ['field' => 'follow_type', 'value' => 4, 'type' => '=']

        ];

        $followModel = new FollowRecord();

        $data        = $followModel->getDataList($request);

        if (!$data) {

            $this->error = $followModel->getError();

            return [];

        }

        return $data;

    }



    /**

     * 订单操作记录

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-10 9:33

     */

    public function getOrderRecordList(array $request): array

    {

        $orderId = $request['order_id'] ?? 0;

        if (!$orderId) {

            $this->error = '参数错误';

            return [];

        }



        $page  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $limit = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        return $this->getActionRecordListByPage($orderId, 'shop', 'order', 0, $page, $limit);

    }



    /**

     * 选择客户

     * @param  array $request 请求参数

     * @return array

     * @author Mr.Liu Wuchen

     * @create 2021-08-05 13:57

     */

    public function getCustomerDataList(array $request): array

    {

        try {

            $userId = $request['user_id'] ?? 0;

            $name = isset($request['name']) && trim($request['name']) ? trim($request['name']) : '';

            $list = [];

            if ($name) {


                // 获取客户数据权限 的客户ID

                $dataAuthCustomerId = (new \app\crm\model\Customer())->getDataAuthCustomer($userId, 'order');


                $where = [

                    ['name', 'like', '%' . $name . '%']

                ];

                !in_array('all', $dataAuthCustomerId) && array_push($where, ['customer_id', 'in', $dataAuthCustomerId]);

                $field = ['customer_id', 'name'];

                $list = (new \app\crm\model\Customer())->getCustomerList($where, $field);

            }



            $this->error = '获取客户成功';

            $data['data'] = $list ?: [];

            return $data;

        } catch (\Exception $e) {

        }



        $this->error = '获取客户失败';

        return [];

    }



    /**

     * 锁定订单

     * @param  array $request 请求参数

     * @return array

     * @author LIU

     * @create 2021-10-26

     */

    public function lcokOrderData($request)

    {



        try {

            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $request = $this->fmtRequest($request);



            $map     = $request['map'] ?? [];

            $where   = [];

            if (!isset($map['type']))

            {

                $this->error = '请传入type类型';

                return [];

            }

            if (!in_array($map['type'],[1,2,3]))

            {

                $this->error = 'type类型不正确';

                return [];

            }



            $type      =$map['type']; // 订单类型 1退款单 2退货单 3收款单

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            //$refund_order_no     = isset($map['refund_order_no']) && $map['refund_order_no'] ? trim($map['refund_order_no']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            // 获取客户数据权限 的客户名称

            if ($shopIds)

            {

                array_push($where, ['shop_id', 'in', $shopIds]);

            }

            if ($uid)

            {

                //门店id搜索

                array_push($where, ['uid', '=', $uid]);

            }

            if ($type)

            {

                //门店名称搜索

                array_push($where, ['type', '=', $type]);

            }

            if ($shop_id)

            {

                //门店名称搜索

                array_push($where, ['shop_id', '=', $shop_id]);

            }

            if ($consignee) {

                // 客户名称搜索

                array_push($where, ['consignee', 'like', '%'.$consignee.'%']);

            }



            if ($shop_name)

            {

                //门店名称搜索

                array_push($where, ['shop_name', 'like', '%'.$shop_name.'%']);

            }

            // 时间

            if($start_time && $end_time)

            {

                array_push($where, ['deal_time', 'between', "$start_time,$end_time"]);

            }



            if ($business_type)

            {

                //业务类型搜索

                array_push($where, ['business_type', '=', $business_type]);

            }

            if ($order_type)

            {

                //订单类型搜索

                array_push($where, ['order_type', '=', $order_type]);

            }

            //退货单以订单总额搜索

            if ($type==2)

            {

                if ($low_total && !$large_total)

                {

                    array_push($where, ['total_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['total_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['total_amount', 'between', "$low_total,$large_total"]);

                }

            }else

            {

                //收款单 退款单以实际金额搜索

                if ($low_total && !$large_total)

                {

                    array_push($where, ['pay_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['pay_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['pay_amount', 'between', "$low_total,$large_total"]);

                }

            }



            $sqlQuery = $this->where($where);

            $dataCount  = $sqlQuery->count();

            $bool=0;

            if ($dataCount) {

                $bool = $sqlQuery->update(['is_lock' => 1]);

            }

            $this->error = '锁定成功'.$bool.'单';

            $data              = [];

            $data['dataCount'] = $bool ?? 0;

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }


    /**

     * 未支付订单列表查询

     * @param  array $request 请求参数

     * @return array

     * @author LIU

     * @create 2021-10-26

     */
    public function getUnpaidList($request)
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";

        try {
            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $request = $this->fmtRequest($request);



            $map     = $request['map'] ?? [];

            $where   = [];

            if (!isset($map['type']))

            {

                $this->error = '请传入type类型';

                return [];

            }

            if (!in_array($map['type'],[1,2,3]))

            {

                $this->error = 'type类型不正确';

                return [];

            }



            $id = isset($map['id']) && $map['id'] ? $map['id'] : [];

            if ($id) {

                if (!is_array($id)) {

                    $id = [$id];

                }

                array_push($where, ['o.id', 'in', $id]);

            }

            array_push($where, ['o.status', '<>', 3]);//排除已作废的

            $type      =$map['type']; // 订单类型 1退款单 2退货单 3收款单

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            //$refund_order_no     = isset($map['refund_order_no']) && $map['refund_order_no'] ? trim($map['refund_order_no']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $status       = isset($map['status']) && intval($map['status']) ? intval($map['status']) : 0; // 订单状态

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            $is_pay = $map['is_pay'] ?? ''; // 订单是否支付


            // 获取客户数据权限 的客户名称

            if ($shopIds)

            {

                array_push($where, ['o.shop_id', 'in', $shopIds]);

            }

            if ($uid)

            {

                //门店id搜索

                array_push($where, ['o.uid', '=', $uid]);

            }

            if ($type)

            {

                //门店名称搜索

                array_push($where, ['o.type', '=', $type]);

            }

            if ($shop_id)

            {

                //门店名称搜索

                array_push($where, ['o.shop_id', '=', $shop_id]);

            }

            if ($consignee) {

                // 客户名称搜索

                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);

            }



            if ($shop_name)

            {

                //门店名称搜索

                array_push($where, ['o.shop_name', 'like', '%'.$shop_name.'%']);

            }

            if ($consignee) {

                // 客户搜索

                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);

            }

            if ($status != -1) {

                array_push($where, ['o.status', '=', $status]);

            }

            if ($is_pay == '0') {

                array_push($where, ['o.is_pay', '=', $is_pay]);

            }


            // 时间

            if($start_time && $end_time)

            {

                array_push($where, ['o.deal_time', 'between', "$start_time,$end_time"]);

            }



            if ($business_type)

            {

                //业务类型搜索

                array_push($where, ['o.business_type', '=', $business_type]);

            }

            if ($order_type)

            {

                //订单类型搜索

                array_push($where, ['o.order_type', '=', $order_type]);

            }

            //退货单以订单总额搜索

            if ($type==2)

            {

                if ($low_total && !$large_total)

                {

                    array_push($where, ['o.total_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['o.total_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['o.total_amount', 'between', "$low_total,$large_total"]);

                }

            }else

            {

                //收款单 退款单以实际金额搜索

                if ($low_total && !$large_total)

                {

                    array_push($where, ['o.pay_amount', 'egt', $low_total]);

                }

                if (!$low_total && $large_total)

                {

                    array_push($where, ['o.pay_amount', 'elt', $large_total]);

                }

                if ($low_total && $large_total)

                {

                    array_push($where, ['o.pay_amount', 'between', "$low_total,$large_total"]);

                }

            }



            $sqlQuery = $this->alias('o')

                ->where($where);

            $dataCount  = $sqlQuery->count();

            $sum_ben_amount=0;

            $sum_zeng_amount=0;

            $sum_amount  =0;

            // echo $dataCount;

            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";

            // exit;

            if ($dataCount) {

                // 订单列表

                //退款单 收款单

                if (in_array($type,[1,3]))

                {

                    $sum_ben_amount  = $sqlQuery->sum('o.pay_amount');

                    $sum_zeng_amount  = $sqlQuery->sum('o.gift_amount');

                    $field = ['o.id','o.consignee', 'o.order_type','o.is_lock','o.business_type','o.shop_name','o.create_time','o.shop_id','o.deal_time','o.type','o.type','o.sale_name','c.king_no','o.pay_amount as pay_price','o.gift_amount as gift_price','o.refund_type','o.refund_type_plus','o.shop_transfer_amount as shop_transfer_price'];

                    $list = $sqlQuery->field($field)

                        ->join('customer c', 'o.uid = c.id')

                        // ->join('shop_refund_order_goods g', 'o.id = g.order_id')

                        ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                        ->order('id DESC')

                        ->select()->toArray();

                }

                if ($list) {
                    //,'g.refund_mode_name'

                    foreach($list as &$v){

                        $v['proceeds'] = bcadd($v['shop_transfer_price'],$v['pay_price'],2);

                        $v['order_type']=$v['order_type']==1?'新单':'补单';

                        $v['business_type']=$v['business_type']==1?'疤痕':'项目';

                        if($v['refund_type']=='101.01'){
                            $refund_type = '店面转诊';
                        }elseif ($v['refund_type']=='101.02') {
                            $refund_type = '退款';
                        }else {
                            $refund_type = '退款调整';
                        }

                        $v['refund_type']=$refund_type;

                        $v['deal_time']=date('Y-m-d', $v['deal_time']);

                        $where = [];

                        array_push($where,['order_id','=',$v['id']]);

                        $refund_goods = Db::name('shop_refund_order_goods')->where($where)->select()->toArray();

                        $v['refund_mode_name'] = $refund_goods[0]['refund_mode_name'];

                    }

                }

            }



            $permission = get_user_permission_menu($userId,'order_list_tag');



            $data              = [];

            $data['menu_list'] = $permission ? $permission : [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            if($start_time && $end_time) {

                if (in_array($type, [1, 3])) {

                    $data['sum_ben_amount'] = $sum_ben_amount ?? 0;

                    $data['sum_zeng_amount'] = $sum_zeng_amount ?? 0;

                } else {

                    $data['sum_amount'] = $sum_amount ?? 0;

                }

            }

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }
    }


    /**
     * 客户数据分析表
     */
    public function getAnalysis2($request)
    {
        $start_time = strtotime($request['start_time']);
        $end_time = strtotime($request['end_time']);
        $type = $request['type']??"";
        $where = [];
        array_push($where,['date','>=',$start_time]);
        array_push($where,['date','<=',$end_time]);
        if(!empty($request['shopIds']))
        {
            array_push($where,['a.shop_id','in',$request['shopIds']]);
        }
        if(!empty($type))
        {
            array_push($where,['b.type','=',$type]);
        }
        $data = Db::name('shop_customer_analyse')->alias('a')
            ->join('shop b','a.shop_id = b.shop_id','left')
            ->field('a.shop_id,sum(a.bh_store) as bh_store,sum(a.dd_store) as dd_store,sum(a.xm_store) as xm_store,sum(a.store_sum) as store_sum,sum(a.bh_receive) as bh_receive,sum(a.dd_receive) as dd_receive,sum(a.xm_receive) as xm_receive
            ,sum(a.receive_sum) as receive_sum,sum(a.bh_receive_deal) as bh_receive_deal,sum(a.dd_receive_deal) as dd_receive_deal,sum(a.xm_receive_deal
            ) as xm_receive_deal,sum(a.receive_deal_sum) as receive_deal_sum,sum(a.bh_receive_money) as bh_receive_money,sum(a.dd_receive_money) as dd_receive_money,sum(a.xm_receive_money) as xm_receive_money
            ,sum(a.receive_money_sum) as receive_money_sum,sum(a.bh_direct) as bh_direct,sum(a.dd_direct) as dd_direct,sum(a.xm_direct) as xm_direct,sum(a.direct_sum) as direct_sum
            ,sum(a.bh_direct_money) as bh_direct_money,sum(a.dd_direct_money) as dd_direct_money,sum(a.xm_direct_money) as xm_direct_money,sum(a.direct_money_sum) as direct_money_sum,b.shop_name,b.market_name,b.market_id')
            ->where($where)
            ->group('shop_id')
            ->order('b.market_name')
            ->select()->toArray();
        $totalData = Db::name('shop_customer_analyse')->alias('a')
            ->join('shop b','a.shop_id = b.shop_id','left')
            ->field('sum(a.bh_store) as bh_store,sum(a.dd_store) as dd_store,sum(a.xm_store) as xm_store,sum(a.store_sum) as store_sum,sum(a.bh_receive) as bh_receive,sum(a.dd_receive) as dd_receive,sum(a.xm_receive) as xm_receive
            ,sum(a.receive_sum) as receive_sum,sum(a.bh_receive_deal) as bh_receive_deal,sum(a.dd_receive_deal) as dd_receive_deal,sum(a.xm_receive_deal
            ) as xm_receive_deal,sum(a.receive_deal_sum) as receive_deal_sum,sum(a.bh_receive_money) as bh_receive_money,sum(a.dd_receive_money) as dd_receive_money,sum(a.xm_receive_money) as xm_receive_money
            ,sum(a.receive_money_sum) as receive_money_sum,sum(a.bh_direct) as bh_direct,sum(a.dd_direct) as dd_direct,sum(a.xm_direct) as xm_direct,sum(a.direct_sum) as direct_sum
            ,sum(a.bh_direct_money) as bh_direct_money,sum(a.dd_direct_money) as dd_direct_money,sum(a.xm_direct_money) as xm_direct_money,sum(a.direct_money_sum) as direct_money_sum')
            ->where($where)
            ->select()->toArray();
        if($totalData)
        {
            $totalData[0]['shop_id']=0;
            $totalData[0]['shop_name']="";
            $totalData[0]['market_name']="汇总";
            $totalData[0]['market_id']=9999;
            $data = array_merge($data,$totalData);
        }
        $result = [];
        foreach($data as $key =>$value)
        {
            $data[$key]['money_sum'] = $value['receive_money_sum']+$value['direct_money_sum'];
            if(empty($value['bh_store']))
            {
                $data[$key]['bh_rate'] = 0;
            }else{
                $data[$key]['bh_rate'] = ($value['bh_receive_deal']+$value['bh_direct'])/$value['bh_store'];
            }
            $data[$key]['bh_rate'] = round($data[$key]['bh_rate'],4)*100;
            $data[$key]['bh_rate'].="%";
            if(empty($value['dd_store']))
            {
                $data[$key]['dd_rate'] = 0;
            }else{
                $data[$key]['dd_rate'] = ($value['dd_receive_deal']+$value['dd_direct'])/$value['dd_store'];
            }
            $data[$key]['dd_rate'] = round($data[$key]['dd_rate'],4)*100;
            $data[$key]['dd_rate'].="%";
            if(empty($value['xm_store']))
            {
                $data[$key]['xm_rate'] = 0;
            }else{
                $data[$key]['xm_rate'] = ($value['xm_receive_deal']+$value['xm_direct'])/$value['xm_store'];
            }
            $data[$key]['xm_rate'] = round($data[$key]['xm_rate'],4)*100;
            $data[$key]['xm_rate'].="%";
            if(empty($request['export']))
            {
                if(empty($result[$value['market_id']]))
                {
                    $result[$value['market_id']]['market_name']=$value['market_name'];
                    $result[$value['market_id']]['list']=[];
                }
                array_push($result[$value['market_id']]['list'],$data[$key]);
            }else{
                array_push($result,$data[$key]);
            }
        }
        $result = array_merge($result,[]);
        return $result;
    }


	public function getAnalysis($request)
	{
	    $bh = [1, 2, 3, 4, 5, 6, 7, 8,655,656];
	    $dd = [10];
	    $xm = [9,11, 12];
	    $type = $request['type']??"";
	    $start_time = strtotime($request['start_time']);
	    $end_time = strtotime($request['end_time']);
	    $data = [];
	    $baseWhere = [];
	    $whereOr = [];
	    $whereType = [];
	    array_push($whereOr, ['a.first_time', 'between', [$start_time, $end_time]]);
	    array_push($whereOr, ['a.second_time', 'between', [$start_time, $end_time]]);
	    if (!empty($request['shopIds'])) {
	        array_push($baseWhere, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    if (!empty($type)) {
	        array_push($whereType, ['sh.type', '=', $type]);
	    } else {
	        array_push($whereType, ['sh.type', '>', 0]);
	    }
	    $where = array_merge($baseWhere, [['b.customer_setting_id_type', 'in', $bh]]);
	    //进店数量明细
	    //疤痕
	    $res = Db::name('customer')->alias('a')
	        ->join('customer_scar b', 'a.id = b.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->field('count(distinct a.id) as num,a.shop_id,sh.shop_name,sh.market_name,sh.market_id')
	        ->where($whereType)
	        ->where($where)
	        ->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })
	        ->group('a.shop_id')
	        ->order('sh.market_id')
	        ->select()->toArray();

	    foreach ($res as $value) {
	        $data[$value['shop_id']]['date'] = $start_time;
	        $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
	        $data[$value['shop_id']]['bh_store'] = $value['num'];
	        $data[$value['shop_id']]['market_id'] = $value['market_id'];
	        $data[$value['shop_id']]['shop_name'] = $value['shop_name'];
	        $data[$value['shop_id']]['market_name'] = $value['market_name'];
	    }

	    //痘痘
	    $where = array_merge($baseWhere, [['b.customer_setting_id_type', 'in', $dd]]);
	    $res = Db::name('customer')->alias('a')
	        ->join('customer_scar b', 'a.id = b.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->field('count(a.id) as num,a.shop_id,sh.shop_name,sh.market_name,sh.market_id')
	        ->where($whereType)
	        ->where($where)
	        ->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })
	        ->group('a.shop_id')
	        ->order('sh.market_id')
	        ->select()->toArray();

	    foreach ($res as $value) {
	        $data[$value['shop_id']]['date'] = $start_time;
	        $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
	        $data[$value['shop_id']]['dd_store'] = $value['num'];
	        $data[$value['shop_id']]['market_id'] = $value['market_id'];
	        $data[$value['shop_id']]['shop_name'] = $value['shop_name'];
	        $data[$value['shop_id']]['market_name'] = $value['market_name'];
	    }
	    //项目
	    $where = array_merge($baseWhere, [['b.customer_setting_id_type', 'in', $xm]]);
	    $res = Db::name('customer')->alias('a')
	        ->join('customer_scar b', 'a.id = b.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->field('count(a.id) as num,a.shop_id,sh.shop_name,sh.market_name,sh.market_id')
	        ->where($whereType)
	        ->where($where)
	        ->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })
	        ->group('a.shop_id')
	        ->order('sh.market_id')
	        ->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['date'] = $start_time;
	        $data[$value['shop_id']]['shop_id'] = $value['shop_id'];
	        $data[$value['shop_id']]['xm_store'] = $value['num'];
	        $data[$value['shop_id']]['market_id'] = $value['market_id'];
	        $data[$value['shop_id']]['shop_name'] = $value['shop_name'];
	        $data[$value['shop_id']]['market_name'] = $value['market_name'];
	    }


	    //体验数量 疤痕
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 168]);
	    array_push($where, ['c.customer_setting_id_type', 'in', $bh]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('customer_scar c', 'a.id = c.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();

	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_receive'] = $value['num'];
	    }

	    //体验数量 痘痘
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 150]);
	    array_push($where, ['c.customer_setting_id_type', 'in', $dd]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('customer_scar c', 'a.id = c.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_receive'] = $value['num'];
	    }

	    //体验数量 项目
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 165]);
	    array_push($where, ['c.customer_setting_id_type', 'in', $xm]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('customer_scar c', 'a.id = c.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(b.customer_id)) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_receive'] = $value['num'];
	    }

	    //体验成交数量
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 168]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $bh]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_receive_deal'] = $value['num'];
	    }

	    $where = [];
	    array_push($where, ['b.goods_id', '=', 150]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $dd]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_receive_deal'] = $value['num'];
	    }

	    $where = [];
	    array_push($where, ['b.goods_id', '=', 165]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $xm]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_receive_deal'] = $value['num'];
	    }

	    //体验成交金额
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 168]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $bh]);
	    array_push($where, ['c.business_type', '=', 1]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 0]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();

	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_receive_money'] = $value['num'];
	    }
	    $where = [];
	    array_push($where, ['b.goods_id', '=', 150]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $dd]);
	    array_push($where, ['c.business_type', '=', 1]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 1]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_receive_money'] = $value['num'];
	    }

	    $where = [];
	    array_push($where, ['b.goods_id', '=', 165]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $xm]);
	    array_push($where, ['c.business_type', '=', 2]);
	    array_push($where, ['c.status', '=', 2]);
	    // array_push($where,['c.extra_type','=',0]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_receive_money'] = $value['num'];
	    }

	    //直接成交人数
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $bh]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_direct'] = $value['num'];
	    }
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $dd]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_direct'] = $value['num'];
	    }
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['a.cj_money', '>', 500]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $xm]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        // ->join('shop_refund_order c','a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,count(distinct(a.id)) as num')->group('a.shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_direct'] = $value['num'];
	    }
	    //直接成交金额
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $bh]);
	    array_push($where, ['c.business_type', '=', 1]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 0]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['bh_direct_money'] = $value['num'];
	    }
	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $dd]);
	    array_push($where, ['c.business_type', '=', 1]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 1]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['dd_direct_money'] = $value['num'];
	    }

	    $where = [];
	    array_push($where, ['b.goods_id', 'not in', [168, 165, 150]]);
	    array_push($where, ['d.customer_setting_id_type', 'in', $xm]);
	    array_push($where, ['c.business_type', '=', 2]);
	    array_push($where, ['c.status', '=', 2]);
	    array_push($where, ['c.extra_type', '=', 0]);
	    if (!empty($request['shopIds'])) {
	        array_push($where, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    $res = Db::name('customer')->alias('a')
	        ->join('service_log b', 'a.id = b.customer_id', 'left')
	        ->join('shop_refund_order c', 'a.id = c.uid')
	        ->join('customer_scar d', 'a.id = d.customer_id', 'left')
	        ->join('shop sh', 'a.shop_id = sh.shop_id', 'left')
	        ->where($whereType)
	        ->where($where)->where(function ($query) use ($whereOr) {
	            $query->whereOr($whereOr);
	        })->field('a.shop_id,sum(c.pay_amount) as num')->group('shop_id')->select()->toArray();
	    foreach ($res as $value) {
	        $data[$value['shop_id']]['xm_direct_money'] = $value['num'];
	    }
	    $start_time = strtotime($request['start_time']);
	    $end_time = strtotime($request['end_time']);
	    $type = $request['type'] ?? "";
	    $totalWhere = [];
	    array_push($totalWhere, ['date', '>=', $start_time]);
	    array_push($totalWhere, ['date', '<=', $end_time]);
	    if (!empty($request['shopIds'])) {
	        array_push($totalWhere, ['a.shop_id', 'in', $request['shopIds']]);
	    }
	    if (!empty($type)) {
	        array_push($totalWhere, ['b.type', '=', $type]);
	    }
	    $totalData[0] = [
	        'bh_store' => 0,
	        'dd_store' => 0,
	        'xm_store' => 0,
	        'bh_receive' => 0,
	        'dd_receive' => 0,
	        'xm_receive' => 0,
	        'bh_receive_deal' => 0,
	        'dd_receive_deal' => 0,
	        'xm_receive_deal' => 0,
	        'receive_deal_sum' => 0,
	        'bh_receive_money' => 0,
	        'dd_receive_money' => 0,
	        'xm_receive_money' => 0,
	        'receive_money_sum' => 0,
	        'bh_direct' => 0,
	        'dd_direct' => 0,
	        'xm_direct' => 0,
	        'direct_sum' => 0,
	        'bh_direct_money' => 0,
	        'dd_direct_money' => 0,
	        'xm_direct_money' => 0,
	        'direct_money_sum' => 0,
	    ];
	    foreach ($data as $hz) {
	        if(array_key_exists('bh_store',$hz)){
	            $totalData[0]['bh_store'] += $hz['bh_store'];
	        }
	        if(array_key_exists('dd_store',$hz)){
	            $totalData[0]['dd_store'] += $hz['dd_store'];
	        }
	        if(array_key_exists('xm_store',$hz)){
	            $totalData[0]['xm_store'] += $hz['xm_store'];
	        }
	        if(array_key_exists('bh_receive',$hz)){
	            $totalData[0]['bh_receive'] += $hz['bh_receive'];
	        }
	        if(array_key_exists('dd_receive',$hz)){
	            $totalData[0]['dd_receive'] += $hz['dd_receive'];
	        }
	        if(array_key_exists('xm_receive',$hz)){
	            $totalData[0]['xm_receive'] += $hz['xm_receive'];
	        }
	        if(array_key_exists('bh_receive_deal',$hz)){
	            $totalData[0]['bh_receive_deal'] += $hz['bh_receive_deal'];
	        }
	        if(array_key_exists('dd_receive_deal',$hz)){
	            $totalData[0]['dd_receive_deal'] += $hz['dd_receive_deal'];
	        }
	        if(array_key_exists('xm_receive_deal',$hz)){
	            $totalData[0]['xm_receive_deal'] += $hz['xm_receive_deal'];
	        }
	        if(array_key_exists('receive_deal_sum',$hz)){
	            $totalData[0]['receive_deal_sum'] += $hz['receive_deal_sum'];
	        }
	        if(array_key_exists('bh_receive_money',$hz)){
	            $totalData[0]['bh_receive_money'] += $hz['bh_receive_money'];
	        }
	        if(array_key_exists('dd_receive_money',$hz)){
	            $totalData[0]['dd_receive_money'] += $hz['dd_receive_money'];
	        }
	        if(array_key_exists('xm_receive_money',$hz)){
	            $totalData[0]['xm_receive_money'] += $hz['xm_receive_money'];
	        }
	        if(array_key_exists('receive_money_sum',$hz)){
	            $totalData[0]['receive_money_sum'] += $hz['receive_money_sum'];
	        }
	        if(array_key_exists('bh_direct',$hz)){
	            $totalData[0]['bh_direct'] += $hz['bh_direct'];
	        }
	        if(array_key_exists('dd_direct',$hz)){
	            $totalData[0]['dd_direct'] += $hz['dd_direct'];
	        }
	        if(array_key_exists('xm_direct',$hz)){
	            $totalData[0]['xm_direct'] += $hz['xm_direct'];
	        }
	        if(array_key_exists('direct_sum',$hz)){
	            $totalData[0]['direct_sum'] += $hz['direct_sum'];
	        }
	        if(array_key_exists('bh_direct_money',$hz)){
	            $totalData[0]['bh_direct_money'] += $hz['bh_direct_money'];
	        }
	        if(array_key_exists('dd_direct_money',$hz)){
	            $totalData[0]['dd_direct_money'] += $hz['dd_direct_money'];
	        }
	        if(array_key_exists('xm_direct_money',$hz)){
	            $totalData[0]['xm_direct_money'] += $hz['xm_direct_money'];
	        }
	        if(array_key_exists('direct_money_sum',$hz)){
	            $totalData[0]['direct_money_sum'] += $hz['direct_money_sum'];
	        }
	    }
	    if ($totalData) {
	        $totalData[0]['shop_id'] = 0;
	        $totalData[0]['shop_name'] = "";
	        $totalData[0]['market_name'] = "汇总";
	        $totalData[0]['market_id'] = 9999;
	        $data = array_merge($data, $totalData);
	    }


	    foreach ($data as $key => $value) {
	        if (empty($value['bh_store'])) {
	            $data[$key]['bh_store'] = 0;
	        }
	        if (empty($value['dd_store'])) {
	            $data[$key]['dd_store'] = 0;
	        }
	        if (empty($value['xm_store'])) {
	            $data[$key]['xm_store'] = 0;
	        }
	        if (empty($value['bh_receive'])) {
	            $data[$key]['bh_receive'] = 0;
	        }
	        if (empty($value['dd_receive'])) {
	            $data[$key]['dd_receive'] = 0;
	        }
	        if (empty($value['xm_receive'])) {
	            $data[$key]['xm_receive'] = 0;
	        }
	        if (empty($value['bh_receive_deal'])) {
	            $data[$key]['bh_receive_deal'] = 0;
	        }
	        if (empty($value['dd_receive_deal'])) {
	            $data[$key]['dd_receive_deal'] = 0;
	        }
	        if (empty($value['xm_receive_deal'])) {
	            $data[$key]['xm_receive_deal'] = 0;
	        }
	        if (empty($value['bh_receive_money'])) {
	            $data[$key]['bh_receive_money'] = 0;
	        }
	        if (empty($value['dd_receive_money'])) {
	            $data[$key]['dd_receive_money'] = 0;
	        }
	        if (empty($value['xm_receive_money'])) {
	            $data[$key]['xm_receive_money'] = 0;
	        }
	        if (empty($value['bh_direct'])) {
	            $data[$key]['bh_direct'] = 0;
	        }
	        if (empty($value['dd_direct'])) {
	            $data[$key]['dd_direct'] = 0;
	        }
	        if (empty($value['xm_direct'])) {
	            $data[$key]['xm_direct'] = 0;
	        }
	        if (empty($value['bh_direct_money'])) {
	            $data[$key]['bh_direct_money'] = 0;
	        }
	        if (empty($value['dd_direct_money'])) {
	            $data[$key]['dd_direct_money'] = 0;
	        }
	        if (empty($value['xm_direct_money'])) {
	            $data[$key]['xm_direct_money'] = 0;
	        }
	        $data[$key]['store_sum'] = $data[$key]['bh_store'] + $data[$key]['dd_store'] + $data[$key]['xm_store'];
	        $data[$key]['receive_sum'] = $data[$key]['bh_receive'] + $data[$key]['dd_receive'] + $data[$key]['xm_receive'];
	        $data[$key]['receive_deal_sum'] = $data[$key]['bh_receive_deal'] + $data[$key]['dd_receive_deal'] + $data[$key]['xm_receive_deal'];
	        $data[$key]['receive_money_sum'] = $data[$key]['bh_receive_money'] + $data[$key]['dd_receive_money'] + $data[$key]['xm_receive_money'];
	        $data[$key]['bh_receive_money'] = round($data[$key]['bh_receive_money'],4);
	        $data[$key]['dd_receive_money'] = round($data[$key]['dd_receive_money'],4);
	        $data[$key]['xm_receive_money'] = round($data[$key]['xm_receive_money'],4);
	        $data[$key]['receive_money_sum'] = round($data[$key]['receive_money_sum'],4);
	        $data[$key]['direct_sum'] = $data[$key]['bh_direct'] + $data[$key]['dd_direct'] + $data[$key]['xm_direct'];
	        $data[$key]['direct_money_sum'] = $data[$key]['bh_direct_money'] + $data[$key]['dd_direct_money'] + $data[$key]['xm_direct_money'];
	        $data[$key]['direct_money_sum'] = round($data[$key]['direct_money_sum'],4);
	        $data[$key]['bh_direct_money'] = round($data[$key]['bh_direct_money'],4);
	        $data[$key]['dd_direct_money'] = round($data[$key]['dd_direct_money'],4);
	        $data[$key]['xm_direct_money'] = round($data[$key]['xm_direct_money'],4);

	        krsort($data[$key]);
	    }

	    $result = [];
	    foreach ($data as $key => $value) {
	        $data[$key]['money_sum'] = $value['receive_money_sum'] + $value['direct_money_sum'];
	        $data[$key]['money_sum'] = round($data[$key]['money_sum'],4);
	        if (empty($value['bh_store'])) {
	            $data[$key]['bh_rate'] = 0;
	        } else {
	            $data[$key]['bh_rate'] = ($value['bh_receive_deal'] + $value['bh_direct']) / $value['bh_store'];
	        }
	        $data[$key]['bh_rate'] = round($data[$key]['bh_rate'], 4) * 100;
	        $data[$key]['bh_rate'] .= "%";
	        if (empty($value['dd_store'])) {
	            $data[$key]['dd_rate'] = 0;
	        } else {
	            $data[$key]['dd_rate'] = ($value['dd_receive_deal'] + $value['dd_direct']) / $value['dd_store'];
	        }
	        $data[$key]['dd_rate'] = round($data[$key]['dd_rate'], 4) * 100;
	        $data[$key]['dd_rate'] .= "%";
	        if (empty($value['xm_store'])) {
	            $data[$key]['xm_rate'] = 0;
	        } else {
	            $data[$key]['xm_rate'] = ($value['xm_receive_deal'] + $value['xm_direct']) / $value['xm_store'];
	        }
	        $data[$key]['xm_rate'] = round($data[$key]['xm_rate'], 4) * 100;
	        $data[$key]['xm_rate'] .= "%";
	        if (empty($request['export'])) {
	            if (empty($result[$value['market_id']])) {
	                $result[$value['market_id']]['market_name'] = $value['market_name'];
	                $result[$value['market_id']]['list'] = [];
	            }
	            array_push($result[$value['market_id']]['list'], $data[$key]);
	        } else {
	            array_push($result, $data[$key]);
	        }
	    }
	    $result = array_merge($result, []);
	    return $result;
	}


	private function callApi($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'cURL Error: '. curl_error($curl);
            return false;
        }
        curl_close($curl);
        return $response;
    }


}

